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;
}
for(auto x : mapping)
cout << mapping.first << " " << mapping.second << endl;
system("pause");
}