0

我在 if 语句中使用 map.find(key) 和 map.end() 函数:

if( p_Repos->returnTypeMap().find(tc[0]) != p_Repos->returnTypeMap().end() ) 

但它不起作用,我收到一个 Microsoft Visual C++ 运行时库错误,告诉我“表达式:列表迭代器不兼容”。tc[0] 只是一个字符串,我的地图中的关键位置是一个字符串。

但是,它们应该是兼容的,对吧?

任何帮助是极大的赞赏。

谢谢,汤姆

编辑:根据此处找到的答案:Finding value in unordered_map,我相信这应该可以正常工作。

第二次编辑:
这是 returnTypeMap() 函数:

std::unordered_map <std::string, std::pair<std::string, std::string>> returnTypeMap()
{
      return typeTable;
}

这是我的地图的定义:

std::unordered_map <std::string, std::pair<std::string, std::string>> typeTable;
4

1 回答 1

5

您正在返回mapby 值,因此每次调用都会评估为完全不同的map. 不同容器中的迭代器不兼容,并且尝试比较它们具有未定义的行为。

尝试更改您的代码以通过const引用返回:

std::unordered_map<std::string, std::pair<std::string, std::string>> const& 
returnTypeMap() const
{
    return typeTable;
}

或制作地图的本地副本并在单个本地副本上调用find和:end

auto typeTable{p_Repos->returnTypeMap()};
if (typeTable.find(tc[0]) != typeTable.end()) {
    //...
}
于 2013-03-16T03:26:11.157 回答