我有以下代码:
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]
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, bothiterator
andconst_iterator
are constant iterators. It is unspecified whether or notiterator
andconst_iterator
are the same type.
关于c++ - 为什么在取消引用 std::set<T>::iterator 时需要 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25931806/