我想在 C++ 中看到 hash_map 示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2179946/
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
I would like to see a hash_map example in C++
提问by skydoor
I don't know how to use the hash function in C++, but I know that we can use hash_map
. Does g++ support that by simply including #include <hash_map>
? What is a simple example using hash_map
?
我不知道如何在 C++ 中使用哈希函数,但我知道我们可以使用hash_map
. g++ 是否通过简单地包含来支持#include <hash_map>
?什么是使用的简单示例hash_map
?
回答by
The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":
当前的 C++ 标准没有哈希映射,但即将到来的 C++0x 标准有,并且 g++ 已经以“无序映射”的形式支持这些映射:
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
int main() {
unordered_map <string, int> m;
m["foo"] = 42;
cout << m["foo"] << endl;
}
In order to get this compile, you need to tell g++ that you are using C++0x:
为了得到这个编译,你需要告诉 g++ 你正在使用 C++0x:
g++ -std=c++0x main.cpp
These maps work pretty much as std::map does, except that instead of providing a custom operator<()
for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.
这些映射的工作方式与 std::map 非常相似,除了不是operator<()
为您自己的类型提供自定义,您需要提供自定义哈希函数 - 为整数和字符串等类型提供了合适的函数。
回答by Nikolai Fetissov
#include <tr1/unordered_map>
will get you next-standard C++ unique hash container. Usage:
#include <tr1/unordered_map>
将为您提供下一个标准的 C++唯一哈希容器。用法:
std::tr1::unordered_map<std::string,int> my_map;
my_map["answer"] = 42;
printf( "The answer to life and everything is: %d\n", my_map["answer"] );
回答by Manuel
回答by Ben
hash_map is a non-standard extension. unordered_map is part of std::tr1, and will be moved into the std namespace for C++0x. http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29
hash_map 是一个非标准的扩展。unordered_map 是 std::tr1 的一部分,将被移动到 C++0x 的 std 命名空间中。http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29
回答by Jerry Coffin
The name accepted into TR1 (and the draft for the next standard) is std::unordered_map
, so if you have that available, it's probably the one you want to use.
TR1(以及下一个标准的草案)接受的名称是std::unordered_map
,所以如果您有可用的名称,它可能就是您想要使用的名称。
Other than that, using it is a lot like using std::map
, with the proviso that when/if you traverse the items in an std::map
, they come out in the order specified by operator<
, but for an unordered_map, the order is generally meaningless.
除此之外,使用它很像 using std::map
,附带条件是,当/如果您遍历 an 中的项目时std::map
,它们会按 指定的顺序出现operator<
,但对于 unordered_map,该顺序通常是没有意义的。