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.

 /*********************************************
Author:Zhou You
Time:2014.09.06
Feature:comparison of containers such as set,multiset,map and multimap.
*********************************************/ #include <iostream>
#include <string>
#include <map>
#include <set> using namespace std; class setdata
{
public:
setdata():
data_(){
}
setdata(int data):
data_(data){
}
~setdata(){} bool operator<(const setdata &data) const{
return data_<data.GetData();
} int GetData() const{
return data_;
} private:
int data_;
}; struct mapcmp
{
bool operator()(const int &data1,const int &data2){
return data1<data2;
}
}; set<setdata> set_int;
multiset<setdata> multiset_int;
map<int,string,mapcmp> map_intstr;
multimap<int,string,mapcmp> multimap_intstr; int main()
{
//for set
set_int.insert(setdata());
set_int.insert(setdata());
set_int.insert(setdata());
set_int.insert(setdata()); cout<<"output set container data"<<endl;
for(set<setdata>::iterator iter = set_int.begin();iter!=set_int.end();++iter){
cout<<iter->GetData()<<" ";
}
cout<<endl<<endl; //for multiset
multiset_int.insert(setdata());
multiset_int.insert(setdata());
multiset_int.insert(setdata());//insert 20 again.
multiset_int.insert(setdata());
multiset_int.insert(setdata()); cout<<"output multiset container data"<<endl;
for(set<setdata>::iterator iter = multiset_int.begin();iter!=multiset_int.end();++iter){
cout<<iter->GetData()<<" ";
}
cout<<endl<<endl; //for map
map_intstr.insert(pair<int,string>(,"chen"));
map_intstr.insert(pair<int,string>(,"wang"));
map_intstr.insert(pair<int,string>(,"wu"));
map_intstr.insert(pair<int,string>(,"tang")); for(map<int,string>::iterator iter = map_intstr.begin();iter!=map_intstr.end();++iter){
cout<<iter->second<<" ";
}
cout<<endl<<endl; //for multimap
multimap_intstr.insert(pair<int,string>(,"chen"));
multimap_intstr.insert(pair<int,string>(,"wang"));
multimap_intstr.insert(pair<int,string>(,"wu"));
multimap_intstr.insert(pair<int,string>(,"wu"));//insert wu again.
multimap_intstr.insert(pair<int,string>(,"tang")); for(map<int,string>::iterator iter = multimap_intstr.begin();iter!=multimap_intstr.end();++iter){
cout<<iter->second<<" ";
}
cout<<endl; return ;
}

  In both map and set,I define compare function myself.

上一篇:20 Zabbix 利用Scripts栏目对Hosts远程执行命令


下一篇:STL之六:map/multimap用法详解