C++ 中的字典/哈希表对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2721315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dictionary/HashTable Object in C++?
提问by cam
I'm looking for a HashTable or Dictionary implementation in C++ that has similar functionality to the one in C#? Does the STL contain an object like this and how would I use it?
我正在寻找 C++ 中的 HashTable 或 Dictionary 实现,其功能与 C# 中的功能相似?STL 是否包含这样的对象,我将如何使用它?
采纳答案by Dean Harding
Actually, to be exactly the same as .NET's Dictionary/Hashtable, what you want is hash_mapor unordered_map(std::map
is implemented as a binary tree), hash_map
is an extension to the SC++L. Most compilers that I know of come with hash_map
, though, and boost obviously has unordered_map
until C++0x is available in all compilers, so you should just be able to use it without trouble.
实际上,与.NET 的Dictionary/Hashtable 完全相同,您想要的是hash_map或unordered_map(std::map
实现为二叉树), hash_map
是SC++L 的扩展。hash_map
不过,我所知道的大多数编译器都带有,而 boost 显然unordered_map
在所有编译器中都可以使用 C++0x 之前,所以您应该能够毫无困难地使用它。
回答by gnud
The STL std::map
can be used to build a dictionary. std::map
is usually implemented as a search tree, not a hash table. That means both lookup and insertion has different perfomance characteristics than C#'s HashMap
- for very large maps, average lookup will be slower, especially if the objects in the map are fragmented in memory.
STLstd::map
可用于构建字典。std::map
通常实现为搜索树,而不是哈希表。这意味着查找和插入都具有与 C# 不同的性能特征HashMap
- 对于非常大的映射,平均查找会更慢,特别是如果映射中的对象在内存中碎片化。
In the TR1 of the new c++ standard, you have std::tr1::unordered_map
and std::tr1::unordered_multimap
, which will usually be implemented using a hash table. If your compiler does not provide those libraries, you can use the implementation from http://www.boost.org/.
在新的 c++ 标准的 TR1 中,您有std::tr1::unordered_map
和std::tr1::unordered_multimap
,通常使用哈希表来实现。如果您的编译器不提供这些库,您可以使用http://www.boost.org/ 中的实现。
Yet another alternative is Google's sparse_hash
.
另一种选择是谷歌的sparse_hash
.