C++中的unordered_map


1.簡介

  隨着C++0x標准的確立,C++的標准庫中也終於有了hash table這個東西。很久以來,STL中都只提供<map>作為存放對應關系的容器,內部通常用紅黑樹實現,據說原因是二叉平衡樹(如紅黑樹)的各種操作,插入、刪除、查找等,都是穩定的時間復雜度,即O(log n);但是對於hash表來說,由於無法避免re-hash所帶來的性能問題,即使大多數情況下hash表的性能非常好,但是re-hash所帶來的不穩定性在當時是不能容忍的。不過由於hash表的性能優勢,它的使用面還是很廣的,於是第三方的類庫基本都提供了支持,比如MSVC中的<hash_map>和Boost中的<boost/unordered_map.hpp>。后來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");
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM