【发布时间】:2014-09-19 10:28:20
【问题描述】:
我有以下代码:
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>&,但为什么会这样呢?该集合包含向量,而不是 const 向量。
【问题讨论】:
-
因为对向量的任何更改都会破坏集合内的顺序
-
cppreference 上有没有关于这个的信息? cplusplus.com/reference/set/set我没看到。
-
第一次提到是在第二段:
The value of the elements in a set cannot be modified once in the container (the elements are always const)然后在会员类型之后:*Note: All iterators in a set point to const elements.原因,为什么一定是这样,网站上没有详细说明。 -
人们有什么理由用 cmets 而不是 answers 回答?
-
@user107986 cppreference 链接将是 en.cppreference.com/w/cpp/container/set -- 你链接到 cplusplus.com
标签: c++ vector iterator stdset