英文:
Using Structs as keys in maps, ignoring == operators, false positive
问题
I'm trying to use a struct as a key in a map, but despite defining <
and ==
operators I'm getting false positives:
return models[mr];
is returning even when the new ImportSettings
has reverse = true
and the one in models has reverse = false
.
The Visual Studio debugger also shows that the operator calls for ==
aren't even being called. What have I misunderstood here?
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 operator==(const ModelReference& other) const
{
return filepath == other.filepath && importSettings == other.importSettings;
}
bool 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];
}
英文:
I'm trying to use a struct as a key in a map, but despite defining <
and ==
operators I'm getting false positives:
return models[mr];
is returning even when the new ImportSettings
has reverse = true
and the one in models has `reverse = false.
The Visual studio debugger also shows that the operator calls for ==
aren't even being called. What have I misunderstood here?
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];
}
答案1
得分: 2
std::map
使用等价性概念。当两个元素等价时,
!(a < b) && !(b < a)
换句话说,map 从不使用 ==
来判断两个元素是否相同。在你的 map 中,当它们具有相同的 filepath
时,两个元素被视为等价。如果你想在 map 的排序中考虑 importSettings
,你需要在 operator<
中也进行比较。
英文:
std::map
uses the concept of equivalence. Two elements are equivalent when
!(a < b) && !(b < a)
In other words, a map never uses ==
to see if two elements are the same. In your map two elements are considered equivalent when they have the same filepath
. If you want to take also importSettings
into account for the ordering in the map you need to compare that also in the operator<
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论