<分区>
为什么我要用 C2440
for(box& b : uset)
Error C2440 'initializing': cannot convert from 'const box' to 'box &'
Error (active) E0433 qualifiers dropped in binding reference of type "box &" to initializer of type "const box"
class box
{
public:
int i = 1;
bool operator==(const box& other) const
{
return true;
}
bool operator!=(const box& other) const
{
return !(*this == other);
}
};
namespace std {
template<>
struct hash<box>
{
size_t operator()(const box& boxObject) const
{
return boxObject.i;
}
};
}
int main()
{
std::unordered_set<box> uset;
for (box& b : uset)
{
}
return 0;
}
我很困惑,好像我将它作为对 const box
的引用,然后问题就消失了。如果我将 unordered_set
换成 vector
那么这不是问题。我不确定这里发生了什么。谁能帮我解释一下。这是关联容器特有的吗?我看到 std::set
也会发生这种情况。