Why do const
STL containers only return const_iterator
s?
For example both std::vector
and std::list
have the method begin
overloaded
as:
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
I thought I could still modify values of a const vector but not the vector itself. According to the standard library there is no difference between:
const std::vector<int>
and
const std::vector<const int>
Suppose you have
instead of
Now, think what happens when you have
You will be able to do something like
which of course shouldn't be legal if you want to preserve logical const-ness. The solution is therefore to make the return type
const_iterator
whenever you invoke iterators onconst
instances.The situation is similar to having
const
classes that have pointer members. In those cases, you may modify the data the pointer points to (but not the pointer itself), so logical const-ness is not preserved. The standard library took a step forward and disallowed these kind of modifications on standard containers viaconst
overloads that returnconst_iterator
s.