Smart Recent Blog Post List

Sep 9, 2011

Iterator in C++

Iterator an object which help in traversing a container. Its like a navigator.
For beginners its very difficult to digest/learn Iterator after Array. Since access to array is very easy just pass an index and get the value.
So this post will help beginners to build understanding about Iterator.

To start with lets look out for simple array traversal.

const int nLength = 10;
int account[nLength] = {0};
//to traverse the array one can simply provide for loop upto length and access it by index
for(int i = 0; i< nLength; i++)
{
cout<<account[i];
}

Now lets solve the above problem if its a list container.

std::list lstAccount; //list container for account
stAccount.push_back(1);
lstAccount.push_back(2);
lstAccount.push_back(3);
lstAccount.push_back(4);
std::list::iterator lstAccountIterator;//iterator for traversing list
for(lstAccountIterator = lstAccount.begin(); //initialize iterator with begining
lstAccountIterator != lstAccount.end(); // traverse until iterator rach end
lstAccountIterator++) //move itertor to next element.
{
cout<<*lstAccountIterator; //print value at itertor
}

So above code will help in traversing a list container.
Some good article on Iterator can be found at following links
       http://www.cplusplus.com/reference/std/iterator/
       http://www.cprogramming.com/tutorial/stl/iterators.html
       http://en.wikipedia.org/wiki/Iterator

Now moving to next level, lets understand the iterator design pattern.

Purpose:
       To provide a way for accessing and traversing the collection of elements, without actually exposing the internal structure/representation of the collection organisation.


Benefits:
     An abstraction which helps in simplifying the traversal mechanism.

Design Layout:
Fig. Iterator Design Pattern
   





1 comments:

Writing this on one query of a newbie, who is facing problem in printing the list :-

lets assume one class say Account, which has methods GetName.

Assuming a list of account
std::list lstAccount;

Account aStudent("Jhony");
lstAccount.push_back(aStudent);

now for printing this list, define an iterator
std::list::iterator lstAccountIterator ;

then defining a loop to traverse it
for(lstAccountIterator = lstAccount.begin(); //initialize iterator with begining
lstAccountIterator != lstAccount.end(); // traverse until iterator rach end
lstAccountIterator++) //move itertor to next element.
{
cout<<(*lstAccountIterator).GetName(); //print value at itertor
}

Post a Comment

Smart Recent Blog Post List