C++中的unordered_map

1.简介

随着C++0x标准的确立,C++的标准库中也终于有了hash table这个东西。很久以来,STL中都只提供

作为存放对应关系的容器,内部通常用红黑树实现,据说原因是二叉平衡树(如红黑树)的各种操作,插入、删除、查找等,都是稳定的时间复杂度,即O(log n);但是对于hash表来说,由于无法避免re-hash所带来的性能问题,即使大多数情况下hash表的性能非常好,但是re-hash所带来的不稳定性在当时是不能容忍的。不过由于hash表的性能优势,它的使用面还是很广的,于是第三方的类库基本都提供了支持,比如MSVC中的和Boost中的。后来Boost的unordered_map被吸纳进了TR1 (C++ Technical Report 1),然后在C++0x中被最终定了标准。

2.示例代码

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

void main(){
    unordered_map<string,int> months;
    //插入数据
    cout<<"insert data"<<endl;
    months["january"]=31;
    months["february"] = 28;
    months["march"] = 31;
    months["september"] = 30;

    //直接使用key值访问键值对,如果没有访问到,返回0
    cout<<"september->"<<months["september"]<<endl;
    cout<<"xx->"<<months["xx"]<<endl;

    typedef unordered_map<int,int> mymap;
    mymap mapping;
    mymap::iterator it;
    mapping[2]=110;
    mapping[5]=220;
    const int x=2;const int y=3;//const是一个C语言(ANSI C)的关键字,它限定一个变量不允许被改变,产生静态作用,提高安全性。

    //寻找是否存在键值对
    //方法一:
    cout<<"find data where key=2"<<endl;
    if( mapping.find(x)!=mapping.end() ){//找到key值为2的键值对
        cout<<"get data where key=2! and data="<<mapping[x]<<endl;
    }
    cout<<"find data where key=3"<<endl;
    if( mapping.find(y)!=mapping.end() ){//找到key值为3的键值对
        cout<<"get data where key=3!"<<endl;
    }
    //方法二:
    it=mapping.find(x);
    printf("find data where key=2 ?  %d\n",(it==mapping.end()));
    it=mapping.find(y);
    printf("find data where key=3 ?  %d\n",(it==mapping.end()));

    //遍历hash table
    for( mymap::iterator iter=mapping.begin();iter!=mapping.end();iter++ ){
        cout<<"key="<<iter->first<<" and value="<<iter->second<<endl;
    }

    system("pause");
}

原文链接: https://www.cnblogs.com/lucio_yz/p/5216249.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/229121

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午2:13
下一篇 2023年2月13日 下午2:13

相关推荐