c++ - 为什么容器需要 const
问题描述
为什么我得到一个 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
.
解决方案
所有关联容器仅提供const
对键类型的访问,因此您无法更改它并破坏容器访问元素的方式。这意味着
decltype(*std::unordered_set<box>{}.begin())
给你一个const box&
。您不能将非 const 引用绑定到 const 对象,因为这会违反 const 正确性,因此代码无法编译。
你需要的是
for (box const& b : uset)
{
}
所以你有一个参考const box
。
向量没有这个问题,因为向量不关心元素的值。它通过索引访问,而不是元素的值,因此更改元素的值不会破坏任何内容。
推荐阅读
- azure-ad-b2c - 登录的用户会话仍然存在,并且不使用不同的电子邮件登录到 Azure AD B2C(在邀请 url 中提到)
- php - 获取变量PHP中的KEY值数组
- rabbitmq - factory.CreateConnection() 生成 None 指定的端点都不可到达;
- python - 如何使用python通过套接字编程发送多个连续值(即视频帧、信号)
- java - 从 jenkins 管道中的指定文件夹运行 jar 文件
- javascript - Javascript:如何在 javascript 中编写递归函数来展开字典对象?
- javascript - 当显示从无设置为块时,Div 中的所有元素都不出现
- android - 升级后对私有依赖做出反应本机 maven 返回 403 Forbidden 或 401 Unathorized
- python - 如何在python fastapi中的普通函数和路由请求函数之间共享全局队列
- apache-spark - spark.driver.extraLibraryPath 覆盖原始库路径