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

sky*_*oor 50 c++ hashmap

我不知道如何在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<()为自己的类型提供自定义,而是需要提供自定义散列函数 - 为整数和字符串等类型提供合适的函数.

  • @Kornel不,我不应该.TR1从未被批准 - tr1命名空间只是某些编译器提供的扩展.我从不在自己的代码中使用它. (2认同)

Nik*_*sov 9

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

  • 欢迎来到真实的世界 :) (23认同)
  • 使用C++风格容器的C风格输出?哎哟! (4认同)