Sunday, October 27, 2013

iterators

Suppose we have a vector consisting of 4 elements. Suppose this is our computer's memory
******************************
******************************
******************************
******************************
******************************
******************************

* shows that at that spot of the memory some data exists.
When we declare a vector and give it 4 elements in memory it is not going to be in some special order. It may be like this
**********v[0]*******v[1]
**********************
***********************
v[3]*******************
********************v[4]
As we can see even if the creators wanted to avoid creating iterator and at the same time they tried to find  a way of calling the elements , they couldn't succeed because the way the elements are scattered in memory is not certain. 
The iterator itself returns you the position of the element we are looking for. It is not an integer, it is a separate data type. It is made in a special way. In our representation of computer memory suppose iterator is a pair of integers defining the row and the column of our element. the iterator for v[0] will be 1 and 12. (1st row and 12th column)
When we add 1 to our iterator (which is a legal move, adding an integer to iterator) the iterator will automatically jump from the 0th element to the 1st element and the new value will be  1 and 20(1st row and 20th column). 

Iterator is defined this way
Data_type_of_our_iterators_target::iterator name_of_iterator;
example
vector<int>::iterator it;
Example of using iterator

for(it=v.begin(); it!=v.end(); it++)
{
       cout<< * it<<endl; ( we wrote * because the iterator itself is a pointer)
}

IF YOU HAVE ANY QUESTIONS LEAVE THEM IN COMMENTS, NO QUESTION WILL STAY UNANSWERED

No comments:

Post a Comment