C++中的哈希容器unordered_map使用示例
随着C++0x标准的确立,C++的标准库中也终于有了hashtable这个东西。
很久以来,STL中都只提供<map>作为存放对应关系的容器,内部通常用红黑树实现,据说原因是二叉平衡树(如红黑树)的各种操作,插入、删除、查找等,都是稳定的时间复杂度,即O(logn);但是对于hash表来说,由于无法避免re-hash所带来的性能问题,即使大多数情况下hash表的性能非常好,但是re-hash所带来的不稳定性在当时是不能容忍的。
不过由于hash表的性能优势,它的使用面还是很广的,于是第三方的类库基本都提供了支持,比如MSVC中的<hash_map>和Boost中的<boost/unordered_map.hpp>。后来Boost的unordered_map被吸纳进了TR1(C++TechnicalReport1),然后在C++0x中被最终定了标准。
于是我们现在就可以开心得写以下的代码了:
#include<iostream>
#include<string>
#include<unordered_map>
intmain()
{
std::unordered_map<std::string,int>months;
months["january"]=31;
months["february"]=28;
months["march"]=31;
months["april"]=30;
months["may"]=31;
months["june"]=30;
months["july"]=31;
months["august"]=31;
months["september"]=30;
months["october"]=31;
months["november"]=30;
months["december"]=31;
std::cout<<"september->"<<months["september"]<<std::endl;
std::cout<<"april->"<<months["april"]<<std::endl;
std::cout<<"december->"<<months["december"]<<std::endl;
std::cout<<"february->"<<months["february"]<<std::endl;
return0;
}
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下