为什么我得到一个 C2440 用于
for(box& b : uset)
错误 C2440 '正在初始化':无法从 'const box' 转换为 'box &'
错误(活动)E0433 限定符在“box &”类型的绑定引用到“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
avector
那么这不是问题。我不确定这里发生了什么。有人可以帮我解释一下。这是关联容器特有的吗?我看到它也发生在std::set
.