Saturday, May 10, 2008

const_iterator : Safety or Necessity?

(Reader Level : Beginner)
(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.

#include <iostream>
#include <vector>

class A
{
private:
std::vector<int> _vector;

public:
void Init()
{
_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[])
{
A a;

a.Init();
a.Display();

std::cout<<"\n\n";
return 0;
}


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.

No comments:

Post a Comment