为什么容器需要常量

Why is const required for a container

本文关键字:常量 为什么      更新时间:2023-10-16

为什么我会得到一个 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的引用.

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