(Knowledge assumptions : const-correctness, std::vector, iterators)
A while back I asked a senior programmer a very naive but valid doubt.
"Are const iterators used only to enforce safety or are there cases where they could be absolutely necessary?"
In reply, this is what I got and the answer was clear.
_vector.push_back( 1 );
_vector.push_back( 2 );
_vector.push_back( 3 );
void Display() const
for(std::vector<int>::const_iterator itr = _vector.begin(); itr != _vector.end(); ++itr)
std::cout << (*itr) << std::endl;
int main(int argc, char *argv)
If we were to try replacing the const_iterator in the Display() function with a normal iterator, the code would simply not compile. This is because the Display() routine is itself const and hence, we must guarantee that no member functions are altered within it. A normal iterator cannot give such a guarantee but a const_iterator can.