c++ - 为什么在取消引用 std::set<T>::iterator 时需要 const?

标签 c++ vector iterator stdset

我有以下代码:

    std::set< std::vector<int> > testSet;
    vector<int> v0 = vector<int>(3);
    vector<int> v11 = vector<int>(3);
    v0[0] = 0;
    v0[1] = 10;
    v0[2] = 20;
    std::cout << v0[0] << endl;
    testSet.insert(v0);
    v0[0] = 1;
    v0[1] = 11;
    v0[2] = 22;
    testSet.insert(v0);
    std::set< std::vector<int> >::iterator it;

    for (it = testSet.begin(); it != testSet.end(); it++) {
        const std::vector<int>& i = (*it); 
        std::cout << i[0] << endl;  
    }

当我改变时:

const std::vector<int>& i = (*it)

到:

std::vector<int>& i = (*it)

它停止工作。显然 (*it)返回 const vector<int>& ,但为什么会这样呢?该集合包含 vector ,而不是 const载体。

最佳答案

这是因为您的实际 testSet声明如下所示:

std::set<std::vector<int>, std::less<std::vector<int>>> testSet;
//                         ~~~~~~~~~~~~~~~~~~~~~~~~~~^

也就是value_type本身用作排序谓词的参数(无论它是 std::less<T> 还是自定义谓词),以及它在 std::set 中的位置数据结构(可能是 RB 树)取决于它的原始值(在 insert 操作时)。 因此,无需重新排序 std::set 即可更改内容会破坏排序逻辑。

非const迭代器的constness在标准中也有提到:

§ 23.2.4 Associative containers [associative.reqmts]

  1. iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type.

关于c++ - 为什么在取消引用 std::set<T>::iterator 时需要 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25931806/

相关文章:

c++ - 从整数数组初始化 vector 的程序。 Cout 出错了?

c++ - 移动语义 C++11(Bjarne Stroustrup 书,第 75 页)

Arraylist 上的 java.util.NoSuchElementException

c++ - std::chrono - 固定时间步长循环

c++ - 一次将多个元素添加到 C++ vector

使用 C++/CLR dll 时 C# 应用程序崩溃

c++ - 如何将值从 safearray 复制到 vector?

c++ - 使用 free 时内存使用量没有减少?

c++ - 空迭代器会导致未定义的行为吗?

java - set.iterator()......我错在哪里?