我不知道如何在C++中使用哈希函数,但我知道我们可以使用hash_map.g ++是否通过简单包含来支持#include <hash_map>?使用什么简单的例子hash_map?
小智 52
当前的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;
}
Run Code Online (Sandbox Code Playgroud)
为了得到这个编译,你需要告诉g ++你正在使用C++ 0x:
g++ -std=c++0x main.cpp
Run Code Online (Sandbox Code Playgroud)
这些映射的工作方式与std :: map相同,只是不需要operator<()为自己的类型提供自定义,而是需要提供自定义散列函数 - 为整数和字符串等类型提供合适的函数.
#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"] );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100793 次 |
| 最近记录: |