What is the difference between a
const_iterator and an
iterator and where would you use one over the other?
const_iterators don't allow you to change the values that they point to, regular
As with all things in C++, always prefer
const, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not
const to change the pointed-to value).
They should pretty much be self-explanatory. If iterator points to an element of type T, then const_iterator points to an element of type 'const T'.
It's basically equivalent to the pointer types:
T* // A non-const iterator to a non-const element. Corresponds to std::vector<T>::iterator T* const // A const iterator to a non-const element. Corresponds to const std::vector<T>::iterator const T* // A non-const iterator to a const element. Corresponds to std::vector<T>::const_iterator
A const iterator always points to the same element, so the iterator itself is const. But the element it points to does not have to be const, so the element it points to can be changed. A const_iterator is an iterator that points to a const element, so while the iterator itself can be updated (incremented or decremented, for example), the element it points to can not be changed.