Const iterators
There's just one more complication to consider, before we abandon this list iterator example. Notice that I quietly changed our count_if
function template so that it takes Container&
instead of const Container&
! That's because the begin()
and end()
member functions we provided are non-const member functions; and that's because they return iterators whose operator*
returns non-const references to the elements of the list. We'd like to make our list type (and its iterators) completely const-correct--that is, we'd like you to be able to define and use variables of type const list_of_ints
, but prevent you from modifying the elements of a const
list.
The standard library generally deals with this issue by giving each standard container two different kinds of iterator: bag::iterator
and bag::const_iterator
. The non-const member function bag::begin()
returns an iterator
and the bag::begin() const
member function returns a const_iterator
. The underscore is all-important! Notice...