C++中的哈希容器unordered_map使用示例

Vivienne ·
更新时间:2024-09-21
· 797 次阅读

随着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中被最终定了标准。

于是我们现在就可以开心得写以下的代码了:

#include <iostream> #include <string> #include <unordered_map> int main() { 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; return 0; } 您可能感兴趣的文章:C++中vector可以作为map的键值实例代码C++如何删除map容器中指定值的元素详解C++中 map的基本操作浅谈c++ vector和map的遍历和删除对象C++中vector和map的删除方法(推荐)浅谈c++中的stl中的map用法详解深入了解C++中map用法VC++中图像处理类CBitmap的用法c++中map的基本用法和嵌套用法实例分析C++标准模板库map的常用操作



c+ unordered_map map 示例 哈希 C++

需要 登录 后方可回复, 如果你还没有账号请 注册新账号