我在 if 语句中使用 map.find(key) 和 map.end() 函数:
if( p_Repos->returnTypeMap().find(tc[0]) != p_Repos->returnTypeMap().end() )
但它不起作用,我收到一个 Microsoft Visual C++ 运行时库错误,告诉我“表达式:列表迭代器不兼容”。 tc[0] 只是一个字符串,而我的 map 中的关键位置是一个字符串。
但是,它们应该是兼容的,对吧?
非常感谢任何帮助。
谢谢, 汤姆
编辑:基于此处找到的答案:Finding value in unordered_map ,我相信这应该是可行的。
第二次编辑:
这是 returnTypeMap() 函数:
std::unordered_map <std::string, std::pair<std::string, std::string>> returnTypeMap()
{
return typeTable;
}
这是我的 map 的定义:
std::unordered_map <std::string, std::pair<std::string, std::string>> typeTable;
最佳答案
您正在按值返回 map
,因此每次调用的计算结果都是完全不同的 map
。不同容器中的迭代器不兼容,尝试比较它们具有未定义的行为。
尝试更改您的代码以通过 const
引用返回:
std::unordered_map<std::string, std::pair<std::string, std::string>> const&
returnTypeMap() const
{
return typeTable;
}
或者制作 map 的本地拷贝并在单个本地拷贝上调用 find
和 end
:
auto typeTable{p_Repos->returnTypeMap()};
if (typeTable.find(tc[0]) != typeTable.end()) {
//...
}
关于c++ - 据说 map.find() 和 map.end() 迭代器不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15445158/