首页 > 代码库 > stuff about set multiset map multimap
stuff about set multiset map multimap
A lot of interviewers like to ask the candidates the difference between set and multiset(map and multimap).What does multi actually mean?Multi-container could have duplicate element.Check the code below.
1 /********************************************* 2 Author:Zhou You 3 Time:2014.09.06 4 Feature:comparison of containers such as set,multiset,map and multimap. 5 *********************************************/ 6 7 #include <iostream> 8 #include <string> 9 #include <map> 10 #include <set> 11 12 using namespace std; 13 14 class setdata 15 { 16 public: 17 setdata(): 18 data_(0){ 19 } 20 setdata(int data): 21 data_(data){ 22 } 23 ~setdata(){} 24 25 bool operator<(const setdata &data) const{ 26 return data_<data.GetData(); 27 } 28 29 int GetData() const{ 30 return data_; 31 } 32 33 private: 34 int data_; 35 }; 36 37 struct mapcmp 38 { 39 bool operator()(const int &data1,const int &data2){ 40 return data1<data2; 41 } 42 }; 43 44 set<setdata> set_int; 45 multiset<setdata> multiset_int; 46 map<int,string,mapcmp> map_intstr; 47 multimap<int,string,mapcmp> multimap_intstr; 48 49 int main() 50 { 51 //for set 52 set_int.insert(setdata(1)); 53 set_int.insert(setdata(20)); 54 set_int.insert(setdata(14)); 55 set_int.insert(setdata(23)); 56 57 cout<<"output set container data"<<endl; 58 for(set<setdata>::iterator iter = set_int.begin();iter!=set_int.end();++iter){ 59 cout<<iter->GetData()<<" "; 60 } 61 cout<<endl<<endl; 62 63 //for multiset 64 multiset_int.insert(setdata(1)); 65 multiset_int.insert(setdata(20)); 66 multiset_int.insert(setdata(20));//insert 20 again. 67 multiset_int.insert(setdata(14)); 68 multiset_int.insert(setdata(23)); 69 70 cout<<"output multiset container data"<<endl; 71 for(set<setdata>::iterator iter = multiset_int.begin();iter!=multiset_int.end();++iter){ 72 cout<<iter->GetData()<<" "; 73 } 74 cout<<endl<<endl; 75 76 //for map 77 map_intstr.insert(pair<int,string>(9,"chen")); 78 map_intstr.insert(pair<int,string>(2,"wang")); 79 map_intstr.insert(pair<int,string>(13,"wu")); 80 map_intstr.insert(pair<int,string>(7,"tang")); 81 82 for(map<int,string>::iterator iter = map_intstr.begin();iter!=map_intstr.end();++iter){ 83 cout<<iter->second<<" "; 84 } 85 cout<<endl<<endl; 86 87 //for multimap 88 multimap_intstr.insert(pair<int,string>(9,"chen")); 89 multimap_intstr.insert(pair<int,string>(2,"wang")); 90 multimap_intstr.insert(pair<int,string>(13,"wu")); 91 multimap_intstr.insert(pair<int,string>(13,"wu"));//insert wu again. 92 multimap_intstr.insert(pair<int,string>(7,"tang")); 93 94 for(map<int,string>::iterator iter = multimap_intstr.begin();iter!=multimap_intstr.end();++iter){ 95 cout<<iter->second<<" "; 96 } 97 cout<<endl; 98 99 return 0;100 }
In both map and set,I define compare function myself.
stuff about set multiset map multimap
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。