我想在C ++中看到一个hash_map的例子

我不知道如何在C ++中使用哈希函数,但是我知道我们可以使用hash_map 。 g ++是否只支持#include <hash_map> ? 什么是使用hash_map的简单示例?

目前的C ++标准没有哈希映射,但是即将出现的C ++ 0x标准,并且已经被g ++以“无序映射”的forms支持:

 #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:

 g++ -std=c++0x main.cpp 

这些地图的工作原理与std :: map差不多,除了不是为自己的types提供自定义operator<() ,而是需要提供自定义哈希函数 – 为整型和stringtypes提供适合的函数。

#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"] ); 

hash_map是一个非标准的扩展。 unordered_map是std :: tr1的一部分,并将被移到std命名空间中,用于C ++ 0x。 http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29

TR1(以及下一个标准的草案)接受的名字是std::unordered_map ,所以如果你有这个可用的,那可能就是你想要使用的名字了。

除此之外,使用它很像使用std::map ,但是当/如果遍历std::map的项时,它们按照operator<指定的顺序出现,但对于unordered_map,顺序通常是没有意义的。