This question already has an answer here:
-
What is the difference between const_iterator and non-const iterator in the C++ STL?
7 answers
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.
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.)
Performance wise there is no difference. The only purpose of having const_iterator
over iterator
is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:
std::vector<int> integers{ 3, 4, 56, 6, 778 };
If we were to read & write the members of a container we will use iterator:
for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
{*it = 4; std::cout << *it << std::endl; }
If we were to only read the members of the container integers
you might wanna use const_iterator which doesn't allow to write or modify members of container.
for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
{ cout << *it << endl; }
NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.
if you have a list a and then following statements
list<int>::iterator it; // declare an iterator
list<int>::const_iterator cit; // declare an const iterator
it=a.begin();
cit=a.begin();
you can change the contents of the element in the list using “it” but not “cit”,
that is you can use “cit” for reading the contents not for updating the elements.
*it=*it+1;//returns no error
*cit=*cit+1;//this will return error