0

Possible Duplicate:
C++ STL set update is tedious: I can't change an element in place

Why does this code complain that my argument is a const_iterator when it's not declared that way?

void foo(std::set<int>::iterator it)
{
  *it=2;
}

I get error: assignment of read-only location ‘it.std::_Rb_tree_const_iterator<_Tp>::operator* with _Tp = int’

Community
  • 1
  • 1
John Gordon
  • 2,576
  • 3
  • 24
  • 29
  • After reading the link, I understand. I don't like it, but it makes sense. – John Gordon Mar 14 '12 at 20:28
  • They did this because otherwise they cannot maintain "the invaraints" (they cannot guarantee it's still sorted), which would make `set` fail to work. – Mooing Duck Mar 14 '12 at 20:41

3 Answers3

3

Because it's a set. Sets use const iterators because you can't change the values without messing up the order of the set.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
3

All set iterators are const. You can't update the value of a set member by assigning through the iterator. You must erase the old value and insert a new one.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

Because in C++11 set<>::iterator is the same as set<>::const_iterator. I.e. you cannot modify elements inside a set.

Eugene
  • 6,194
  • 1
  • 20
  • 31