C++无序映射导致编译时错误

C++ unordered_map causing compile-time error

本文关键字:编译时错误 映射 无序 C++      更新时间:2023-10-16

我有以下内容:

#include<iostream>
#include<unordered_map>
#include<tuple>
using namespace std;
class CTest {
    // Properties
    public:
        unordered_map<const string, tuple<int, int> > Layout;
    // Methods
    public:
        CTest ();
        ~CTest ();
};
CTest::CTest () {
    Layout["XYZ"] = make_tuple (0, 1);
}
CTest::~CTest () {
  // Do nothing
}
int main (int argc, char *argv[]) {
    CTest Test;
    return 0;
}

编译这个简单的程序会出现以下错误:

错误C2678:二进制"==":找不到接受类型为"const std::string"的左侧操作数的运算符(或者没有可接受的转换)

我在Windows7中使用Visual Studio 2010 Professional。

除了将Layout更改为:

unordered_map<string, tuple<int, int> > Layout;

正如Johan和Benjamin所说,您还需要#include <string>

注意,我不明白为什么需要更改Layout,即使const是多余的

您需要删除键上的const限定符。

unordered_map<const string, tuple<int, int> > Layout;

进入

unordered_map<string, tuple<int, int> > Layout;

这是因为密钥总是常量,根据这个答案:

使用const密钥进行无序映射

我认为根本原因与C中允许但C++中不允许的重复常量限定符有关?

此外,正如其他帖子所指出的,您可能需要包括字符串(尽管使用gcc,它似乎与iostream一起提供)

Visual Studio 2010将按照原样编译源代码,只要您使用#include <string>,这样它就可以使用string的比较测试。

正如其他海报所提到的,您也应该将您的密钥设置为常规string,而不是const string,因为这符合STL标准,但这并不是使VS 2010编译上述源代码所必需的。

正如前面所指出的,最初错误的原因是需要包含<string>。然而,您可能会遇到另一个问题:

unordered_map<const string, tuple<int, int> > Layout;

您(可能)需要从该字符串中删除常量:

unordered_map<string, tuple<int, int> > Layout;

这在您的编译器上可能不是必需的,但在我的编译器上却是必需的。首先,const是多余的,map/undered_map键无论如何都是const,但这不是问题所在。这个问题与哈希函数模板不适用于const类型有关。

以下简单的程序为我隔离了问题:

#include <functional>
int main (int argc, char *argv[])
{
    std::hash<const int> h;
    h(10);
}

http://ideone.com/k2vSy

undefined reference to `std::hash<int const>::operator()(int) const'

目前我无法对此作出解释。