what is the difference between const_iterator and iterator?

user658266 picture user658266 · Mar 18, 2011 · Viewed 117.1k times · Source

What is difference between these two regarding implementation inside STL. what is the difference regarding performance? I guess when we are traversing the vector in "read only wise", we prefer const_iterator, right?

Thank you.

Answer

ysdx picture ysdx · Mar 18, 2011

There is no performance difference.

A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value (const T&) and prevents modification of the referenced value: it enforces const-correctness.

When you have a const reference to the container, you can only get a const_iterator.

Edited: I mentionned “The const_iterator returns constant pointers” which is not accurate, thanks to Brandon for pointing it out.

Edit: For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of std::string use COW.)