STL_map_multimap

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值