我想在 C++ 中查看 hash_map 示例
我不知道如何在 C++ 中使用哈希函数,但我知道我们可以使用 hash_map
.g++ 是否通过简单地包含 #include <hash_map>
来支持这一点?什么是使用 hash_map
的简单示例?
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,但是即将到来的C++0x标准有,g++已经以unordered"的形式支持了地图":
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":
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
int main() {
unordered_map <string, int> m;
m["foo"] = 42;
cout << m["foo"] << endl;
}
为了得到这个编译,你需要告诉g++你正在使用C++0x:
In order to get this compile, you need to tell g++ that you are using C++0x:
g++ -std=c++0x main.cpp
这些映射的工作原理与 std::map 非常相似,除了为您自己的类型提供自定义 operator<()
之外,您需要提供自定义哈希函数 - 合适的函数是为整数和字符串等类型提供.
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.
相关文章