【问题标题】:How do you create a hash table in C++?如何在 C++ 中创建哈希表?
【发布时间】:2010-12-01 22:37:23
【问题描述】:

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

#include <map>
std::map <string, char> grade_list;
grade_list["John"] = 'B';

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

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

谢谢!

【问题讨论】:

  • 对于一个小程序,您发布了一些由于缺少主函数而甚至不可能编译的内容,并且缺少诸如 之类的标头
  • @Vatsan - 这就是问题所在。我没有把那个代码放在主函数中。

标签: c++ boost stl map hashtable


【解决方案1】:

首先std::map 是一个树形图,而不是一个哈希图。

您收到错误的原因是您没有#include &lt;string&gt; 也没有限定对string 的引用,因此编译器不知道string 是一个类。

【讨论】:

  • 即将进入 C++0x。
  • 好的,那么如何创建哈希表呢?​​
  • @BSeven:通过使用已经实现 C++0x 的 unordered_map 的编译器(最新版本的 gcc 和 Visual Studio 可以)并使用它或使用 boost's implementation
  • 这就是我想要的。我不知道它叫什么。谢谢!
【解决方案2】:
#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;
}

这对 g++ 非常有效。 您应该在地图声明中的字符串之前指定 std::,就像我在代码中所做的那样。

【讨论】:

    【解决方案3】:

    代码在 main 函数之前。

    【讨论】:

      猜你喜欢
      • 2011-09-20
      • 2015-09-24
      • 2012-01-02
      • 2010-09-06
      • 2010-12-04
      • 2012-02-09
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多