C++无序映射导致编译时错误
C++ unordered_map causing compile-time error
我有以下内容:
#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'
目前我无法对此作出解释。
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 如何在常量计算表达式中获取编译时错误?
- C++根据调用的构造函数强制编译时错误
- 使用 std::iterator_traits<> 时编译时错误不明确
- is_same和variadic模板编译时错误无效转换
- 有没有办法在 C++17 中创建编译时类型映射以进行类型检查?
- 私有运营商删除会触发 GCC 和 Clang 的编译时错误,但不会在 MSVC 上触发编译时错误
- 运行时与编译时多态性:更好的可读性与编译时错误检查,更重要的是
- 引发编译时错误
- 为什么调用不明确的 ctor 时没有编译时错误?
- 在 sizeof 运算符上强制编译时错误
- 未经授权的私有类成员访问会产生编译时错误而不是运行时错误?
- 从Mac上的终端编译时C 错误
- 使用MINGW-W64使用-M32选项(32位代码)编译时错误
- C++线程错误 - 带有类参数的编译时错误
- 如果编译时间构量参数是错误的,则生成编译时错误
- 尝试调用指向成员函数的函数指针时出现编译时错误
- 编译时错误:删除了联合默认构造函数
- 初始化启动对象时出现编译时错误
- C++无序映射导致编译时错误