C++中map容器提供一个键值对容器,map与multimap差别仅仅在于multiple允许一个键对应多个值.
一.map的说明
1.头文件
#include<map.h>
2.定义方法
(1)map<string,int> m;
(2)typedef map<string,int> M;
M m;
3.插入数据
(1)m['a'] = 1
(2)m.insert(map<string,int>::value_type("b",2));
(3)m.insert(pair<string,int>("c",3));
(4)m.insert(make_pair<string,int>("d",4));
4.查找数据和修改数据
(1)int i = m["a"];
m["a"] = i;
(2)m::iterator m_iter;
m.find("b");
int j = m_iter->second;
m_iter->second = j;
!!!注意!!! 键本身是不能被修改的,除非删除.
5.删除数据
(1)m.erase(m_iter);
(2)m.erase("c");
!!!注意!!! 第一种情况在迭代期间是不能被删除的
6 迭代数据
for (m_iter=m.begin(); m_iter!=m.end(); ++m_iter)
{
}
7 其它方法
m.size() 返回元素数目
m.empty() 判断是否为空
m.clear() 清空所有元素
可以直接进行赋值和比较:=, >, >=, <, <=, != 等等
二map的举例
<span style="font-size:18px;">要求: 将mymap中itemstruct的a大于100的项删除 struct itemstruct { int a; char b[20]; }; map<string,itemstruct> mymap;</span>
<span style="font-size:18px;">#include <iostream> #include <ctime> #include <map> using namespace std; typedef struct itemstruct { int a; char b[20]; }itemS; itemS s[4] = {{102,"what"}, {33, "hello"}, {198,"world"}, {45, "c++"} };; int main() { map<string,itemS> mymap; string str[4] = {"1st","2nd","3rd","4th"}; for(int i = 0; i<4; i++) { mymap.insert(make_pair(str[i], s[i])); } map<string,itemS>::iterator it; for(it=mymap.begin(); it!=mymap.end(); it++) { if(it->second.a >100) { i=mymap.erase(it); //----->正确 mymap.erase(it); //----->it失效.. } } //first是Key, second是value; for(it = mymap.begin(); it!=mymap.end(); it++) { cout<<it->first<<" "<<it->second.a<<" "<<it->second.b<<endl; } system("pause"); return 0; } </span>
代码2:
<span style="font-size:18px;">#include<map> #include<iterator> #include<string> #include<iostream> #include<cstring> using namespace std; struct itemstruct { int a; char b[20]; itemstruct(int t,char*str) { a=t; strcpy(b,str); } }; int main() { map<string,itemstruct>mymap; mymap.insert(make_pair("a",itemstruct(10,"hanzhou"))); mymap.insert(make_pair("ab",itemstruct(20,"fuzhou"))); mymap.insert(make_pair("abc",itemstruct(30,"zhengzhou"))); mymap.insert(make_pair("abcd",itemstruct(200,"wuhan"))); mymap.insert(make_pair("abcde",itemstruct(150,"kunming"))); mymap.insert(make_pair("abcdef",itemstruct(50,"xiamen"))); map<string,itemstruct>::iterator it=mymap.begin(); while(it!=mymap.end()) { if((it->second).a>100) mymap.erase(it++); else it++; } it=mymap.begin(); while(it!=mymap.end()) { cout<<it->first<<" "<<(it->second).a<<" "<<(it->second).b<<endl; it++; } system("PAUSE"); return 0; }</span>
代码3:
<span style="font-size:18px;">for(map<string, itemstruct>::iterator i = mymap.begin(); i != mymap.end();) { if(i->second.a > 100) i = mymap.erase(i); else ++i; } </span>