c++ - 为什么容器需要const

标签 c++ for-loop stl

<分区>

为什么我要用 C2440

for(box& b : uset)

Error C2440 'initializing': cannot convert from 'const box' to 'box &'

Error (active) E0433 qualifiers dropped in binding reference of type "box &" to initializer of type "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 引用绑定(bind)到 const 对象,因为这会违反 const 正确性,因此代码无法编译。

你需要的是

for (box const& b : uset)
{

}

所以你有一个对 const box 的引用。

vector 不存在这个问题,因为 vector 不关心元素的值。它按索引访问,而不是按元素的值访问,因此更改元素的值不会破坏任何内容。

关于c++ - 为什么容器需要const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55345946/

相关文章:

c++ - 用于快速查找的最佳 C++ STL 容器是什么?

c++ - "Universal character name conversion"在 C++ 中是什么意思?

javascript - 第二个内含 IF 语句的嵌套循环 (FOR) 仅打印一个结果

windows - 使用 "tokens=*"或 "delims="调用 FOR 在功能上是否等效?

python - 更高效地过滤多个列表和嵌套 for 循环

c++ - 我是否应该假设一个对象的析构函数在从 STL 容器中移除后立即被调用?

c++ - 两个文件中相同函数/全局变量的不同声明

c++ - 程序编译失败

c++ - 如何为文本模板创建 emacs 宏

c++ - std::unordered_set迭代器遍历的复杂度