我不知道如何在 C++ 中使用哈希函数,但我知道我们可以使用 hash_map
. g++ 是否通过简单地包含 #include <hash_map>
来支持它? ?什么是使用 hash_map
的简单示例?
最佳答案
当前的 C++ 标准没有 HashMap ,但即将到来的 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;
}
为了得到这个编译,你需要告诉g++你正在使用C++0x:
g++ -std=c++0x main.cpp
这些 map 的工作原理与 std::map 非常相似,只是没有提供自定义 operator<()
对于您自己的类型,您需要提供自定义哈希函数 - 为整数和字符串等类型提供了合适的函数。
关于c++ - 我想在 C++ 中查看 hash_map 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2179946/