Avoid stl set non-const iterators

This tip submitted by Igor on 2012-07-10 05:53:26. It has been viewed 16989 times.
Rating of 4.9 with 120 votes

#include < set >
int main()
  int v[] = { 1, 2, 3 };
  std::set< int > s(v, v + 3);
  std::set< int >::iterator it = s.begin();
  *it = 4;

The above code uses (or tries to use) a non-const iterator to create a non-sorted set. The code would compile in Visual Studio but not using gcc, for which set::iterator is defined as set::const_iterator to avoid this kind of (ab)use.

Although there are other ways to obtain unsorted sets (e.g. through custom comparison operators or external non-const references/pointers to the elements), my tip is to avoid the use of stl set non-const iterators whenever possible.

More tips

Help your fellow programmers! Add a tip!