首页 > 解决方案 > 为什么容器需要 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_setavector那么这不是问题。我不确定这里发生了什么。有人可以帮我解释一下。这是关联容器特有的吗?我看到它也发生在std::set.

标签: c++for-loopstl

解决方案


所有关联容器仅提供const对键类型的访问,因此您无法更改它并破坏容器访问元素的方式。这意味着

decltype(*std::unordered_set<box>{}.begin())

给你一个const box&。您不能将非 const 引用绑定到 const 对象,因为这会违反 const 正确性,因此代码无法编译。

你需要的是

for (box const& b : uset)
{

}

所以你有一个参考const box

向量没有这个问题,因为向量不关心元素的值。它通过索引访问,而不是元素的值,因此更改元素的值不会破坏任何内容。


推荐阅读