Operations on Iterators in STL

Following are the operations that can be used with Iterators to perform various actions.

  • advance
  • distance
  • next
  • prev
  • begin
  • end

advance() Operation

It will increment the iterator i by the value of the distance. If the value of distance is negative, then iterator will be decremented.

SYNTAX: advance(iterator i ,int distance)


#include<iostream>
#include<vector>

int main()
{
    vector<int>  v(10) ;    // create a vector of 10 0's
    vector<int>::iterator i;  // defines an iterator i to the vector of integers
    
    i = v.begin();
    /* i now points to the beginning of the vector v */
    
    advance(i,5);
    /* i now points to the fifth element form the 
    beginning of the vector v */
    
    advance(i,-1);
    /* i  now points to the fourth element from the 
    beginning of the vector */ 
}



distance() Operation

It will return the number of elements or we can say distance between the first and the last iterator.

SYNTAX: distance(iterator first, iterator last)


#include<iostream>
#include<vector>

int main()
{
    vector<int>  v(10) ;    // create a vector of 10 0's
    vector<int>::iterator i, j;  // defines iterators i,j to the vector of integers  
    
    i = v.begin();
    /* i now points to the beginning of the vector v */
    
    
    j = v.end();
    /* j now points to the end() of the vector v */
    
    cout << distance(i,j) << endl;
    /* prints 10 , */
       
}

next() Operation

It will return the nth iterator to i, i.e iterator pointing to the nth element from the element pointed by i.

SYNTAX: next(iterator i ,int n)


prev() Operation

It will return the nth predecessor to i, i.e iterator pointing to the nth predecessor element from the element pointed by i.

SYNTAX: prev(iterator i, int n)


begin() Operation

This method returns an iterator to the start of the given container.

SYNTAX: begin()


end() Operation

This method returns an iterator to the end of the given container.

SYNTAX: end()