您的位置:首页 > 其它

STL_map_multimap

2014-03-24 16:12 417 查看
map 是A->B, 只能有一个A,不允许后面再由A->C,如果需要A -> B and A ->C ,则需要multimap。

map 可以用[] 来O(1)的寻址,Multimap不可以用[].

map的主要的几个I/O, 有如 insert, find, count..... multimap 多了equal_range, lower_bound, upper_bound, count

性能方面,hashmap 和 map的区别在于,如果find的查找量在100w以上,用hashmap效率高。以下的,还是用map更好的。

map内部应用的红黑树数据结构来构建find机制,二分法查找10w,用不20+次。但是100w以上,应该将重点放在hash构建,这样更快些。

#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
#include <stdlib.h>
using namespace std;

typedef struct{
int index;
string str;
}INFO;
int main(void)
{
//map insert has two methonds
//map.insert(map<int,string>::value_type());
//map.insert(make_pair());

//1st insert method
typedef map<int,string> mapinf;
mapinf map1;
string s1="hello";
map1.insert(map<int,string>::value_type(111,s1));
map1.insert(make_pair(1,s1));
mapinf::iterator it;
for(it=map1.begin();it != map1.end();it++)
cout<<it->first<<" "<<it->second<<endl;

//2nd method
typedef map<string,INFO> infomap;
infomap map2;
INFO info1;
info1.index =1;
info1.str="helloworld";
map2.insert(make_pair("hello",info1));
infomap::iterator it1=map2.begin();
cout<<it1->first<<" "<<it1->second.index
<<" "<<it1->second.str<<endl;

//multimap insert and find
typedef multimap<string,INFO> multiinfomap;
typedef multimap<string,INFO>::iterator multimapit;
multiinfomap multimap1;
INFO info2;
info2.index=2;
info2.str="helloworld2";
multimap1.insert(make_pair("hello",info1));
multimap1.insert(make_pair("hello",info2));

//using lower_bound/upper_bound
multimapit lb=multimap1.lower_bound("hello");
multimapit ub=multimap1.upper_bound("hello");
for(multimapit it=lb;it!=ub;it++){
cout<<it->first<<" "<<it->second.index<<" "<<it->second.str<<endl;
}
//using cnt for multimap
multiinfomap::size_type cnt=multimap1.count("hello");
multimapit iter = multimap1.find("hello");
for(;cnt>0;cnt--,iter++)
cout<<iter->first<<" "<<iter->second.index<<" "<<iter->second.str<<endl;

//using equal range
pair<multimap<string,INFO>::iterator,multimap<string,INFO>::iterator> ret;
ret = multimap1.equal_range("hello");
for(multimapit iter=ret.first;iter != ret.second; iter++)
cout<<iter->first<<" "<<iter->second.index<<" "<<iter->second.str<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: