Maps是一种关联式容器,包含“关键字/值”对。 Multimaps和maps很相似,但是MultiMaps允许重复的元素。
简单介绍:
1、声明,首先包含头文件 “map”
map <int,string> test1,test2;// map <int,string>::iterator it1,it2;//迭代器multimap <int,string> test3;multimap <int,string>::iterator it3;
2、插入数据,可使用三种方法:
第一种,使用pair函数
test1.insert(pair<int,string>(1,"song"));test1.insert(pair<int,string>(2,"zhang"));test1.insert(pair<int,string>(3,"wang"));
第二种,使用value_type类型
test1.insert(map<int,string>::value_type(4,"qian"));test1.insert(map<int,string>::value_type(5,"sun"));
第三种,使用数组方式,,可以覆盖原来数据,前两中不能改变数据,如果存在则插入失败
test1[6] = "mao";test1[7] = "guang";
前两种情况,插入失败后可以通过以下方法检查
//测试是否插入成功pair<map<int,string>::iterator,bool> insert_Pair;insert_Pair = test1.insert(pair<int,string>(1,"Replace"));if (insert_Pair.second == true){cout<<"insert successfully"<<endl;}else{cout<<"insert failure"<<endl;}
3、遍历数据,可使用以下几种方法
第一,正向遍历
for (it1 = test1.begin();it1 != test1.end();it1++){cout<<it1->first<<"-----" << it1->second<<endl;}
第二,逆向遍历,使用反向迭代器
cout<<"反向迭代器"<<endl;//rbegin()指向最后一个元素,rend()指向第一个元素前面,这里++是指往前走一个位置map<int,string>::reverse_iterator reverseIte;for (reverseIte = test1.rbegin();reverseIte != test1.rend();reverseIte++){cout<<reverseIte->first<<"-----" << reverseIte->second<<endl;}
第三,使用数组进行遍历
//使用数组方式进行遍历for (int i = 1;i <= test1.size();i++){cout<<i<<"-----"<<test1[i]<<endl;}
4、查找和判断
第一,使用count进行判断
//count,判断int i=1;for (it1 = test1.begin();it1 != test1.end();i++,it1++){cout<<i;if (test1.count(i)>0)//元素存在 {cout<<"is a element of map"<<endl;}else{cout<<"is not a element of map"<<endl;}}
第二,使用find判断
it2 = test1.find(6);//查找if (it2 != test1.end()){cout<<"find it:"<<it2->first<<"---"<<it2->second<<endl;}else{cout<<"not find it"<<endl;}
5、删除元素
//删除元素it2 = test1.find(2);test1.erase(it2);
这些操作基本上都和set的差不多,好多函数一模一样。