可能重复:
C++ STL set update is tedious: I can't change an element in place
为什么这个代码在没有声明的情况下抱怨我的参数是const_iterator?
void foo(std::set<int>::iterator it)
{
*it=2;
}
我收到错误:指定只读位置'it.std :: _ Rb_tree_const_iterator&lt; _Tp&gt; :: operator * with _Tp = int'
答案 0 :(得分:3)
因为它是set
。设置使用const迭代器,因为你不能在不搞乱集合顺序的情况下更改值。
答案 1 :(得分:3)
所有设置迭代器都是const
。您无法通过迭代器分配来更新集成员的值。您必须erase
旧值和insert
新值。
答案 2 :(得分:1)
因为在C ++ 11中设置&lt;&gt; :: iterator与set&lt;&gt; :: const_iterator相同。即你无法修改集合中的元素。