为什么容器需要常量
Why is const required for a container
为什么我会得到一个 C2440
for(box& b : uset)
错误 C2440"正在初始化":无法从"常量框"转换为"框 &">
错误(活动(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
换成vector
,那就不是问题了。我不确定这里发生了什么。有人可以帮我解释一下吗?这是关联容器特有的吗?我看到它也发生在std::set
.
所有关联容器仅提供对密钥类型的const
访问,因此您无法更改它并破坏容器访问元素的方式。 这意味着
decltype(*std::unordered_set<box>{}.begin())
给你一个const box&
. 您不能将非 const 引用绑定到 const 对象,因为这会违反 const 正确性,因此代码无法编译。
你需要的是
for (box const& b : uset)
{
}
所以你有一个对const box
的引用.
量没有这个问题,因为向量不关心元素的值。 它通过索引而不是元素的值进行访问,因此更改元素的值不会破坏任何内容。
相关文章:
- 为什么我可以通过引用修改常量返回
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 为什么C++常量模板化向量在使用之前没有初始化?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 为什么常量方法可以采用非常量引用?
- 为什么我收到"从常量指针到指针的转换无效?
- 为什么当我们有常量引用时创建临时对象?
- 为什么 std::string_view 比常量字符*快?
- 为什么const_cast和static_cast常量引用没有效果?
- 为什么下面带有非常量转换函数的代码没有歧义?
- 模板推导:为什么函数指针模板定义在常量和/或引用时不匹配?
- 为什么乘以常量有符号整数分数没有优化?
- 为什么"具有常量成员的结构"类型的指针不能指向"具有非常量成员的结构"?
- 为什么在C++使用常量函数时常量是多余的?
- 为什么不能用常量表达式声明数组?
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 为什么在PIMPL中无法访问实现类的常量函数?
- 为什么C++中没有常量引用,就像常量指针一样?
- 为什么编译器在使用"无常量复制构造函数"时抱怨?