Consider the simple program below, which attempts to iterate through the values of a set using NON-const references to the elements in it:
#include
A set is like a map with no values, only keys. Since those keys are used for a tree that accelerates operations on the set, they cannot change. Thus all elements must be const to keep the constraints of the underlying tree from being broken.
std::set
uses the contained values to form a fast data structure (usually, a red-black tree). Changing a value means the whole structure needs to be altered. So, forcing const
ness, std::set
prevents you from pushing it into a non-usable state.
From the cpp reference:
In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container.
The behaviour is by design.
Giving you a non-const iterator could inspire you to change the element in the set; the subsequent iterating behaviour would then be undefined.
Note that the C++ standard says that set<T>::iterator
is const
so the old-fashioned pre C++11 way still wouldn't work.