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的差不多,好多函數一模一樣。