如何在C++中创建哈希表?

B S*_*ven 0 c++ boost stl hashtable map

我在VS 2008 C++中创建一个简单的哈希表.

#include <map>
std::map <string, char> grade_list;
grade_list["John"] = 'B';
Run Code Online (Sandbox Code Playgroud)

我收到错误:错误C2057:预期的常量表达式

那是什么意思?boost库有更好的东西吗?

谢谢!

sep*_*p2k 10

首先std::map是树形图,而不是散列图.

你得到错误的原因是你没有#include <string>或没有限定引用string,因此编译器不知道这string是一个类.

  • <unordered_map>即将推出C++ 0x. (2认同)

Aif*_*Aif 6

#include <map>
#include <iostream>
#include <string>

int main() {
    std::map<std::string, char> grade_list;
    grade_list["John"] = 'B';
    std::cout << grade_list["John"] << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这对g ++很有用.您应该在地图声明中指定std :: before字符串,就像我在代码中所做的那样.