在映射中使用结构作为键,忽略 == 运算符,误报

Using Structs as keys in maps, ignoring == operators, false positive

本文关键字:误报 忽略 运算符 映射 结构      更新时间:2023-10-16

我正在尝试使用结构作为映射中的键,但尽管定义了<==运算符,我还是得到了误报:

即使新ImportSettingsreverse = true并且模型中的具有"反向=假",return models[mr];也会返回。

Visual Studio 调试器还显示,甚至没有调用运算符对==的调用。我在这里误解了什么?

struct HE2_ImportSettings
{
bool reverseWindingOrder = false;
bool operator==(const HE2_ImportSettings& other)const
{
return reverseWindingOrder == other.reverseWindingOrder;
}
};
struct ModelReference
{
std::string filepath = "";
HE2_ImportSettings importSettings = {};
bool ModelReference::operator == (const ModelReference& other) const
{
return filepath == other.filepath && importSettings == other.importSettings;
}
bool ModelReference::operator< (const ModelReference& other) const
{
return filepath < other.filepath;
}
};

ModelReference mr = { filename, importSettings };
bool exists = models.count(mr);
if (exists)
{
//This is returning even when the new importsettings has reverse = true and the one in models has reverse = false
return models[mr];
}

>std::map使用等价的概念。两个元素在以下情况下是等效的

!(a < b) && !(b < a)

换句话说,地图从不使用==来查看两个元素是否相同。在地图中,当两个元素具有相同的filepath时,它们被视为等效。如果您还想importSettings考虑地图中的排序,则需要在operator<中进行比较。