What is the difference between const_iterator and non-const iterator in the C++ STL?


Question

What is the difference between a const_iterator and an iterator and where would you use one over the other?

1
114
4/2/2017 3:48:25 AM

Accepted Answer

const_iterators don't allow you to change the values that they point to, regular iterators do.

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).

102
11/21/2008 5:39:25 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon