C++ Iterator Library - advance



Description

It advances the iterator it by n element positions.

Declaration

Following is the declaration for std::advance.

C++11

template <class InputIterator, class Distance>
  void advance (InputIterator& it, Distance n);

Parameters

  • it − Iterator used in advance.

  • n − It is the number of position to be advanced in iterator.

Return value

none

Exceptions

If any of the arithmetical operations performed on the iterator throws.

Time complexity

constant for random-access iterators.

Example

The following example shows the usage of std::advance.

#include <iostream>     
#include <iterator>     
#include <list>         

int main () {
   std::list<int> mylist;
   for (int i = 0; i < 10; i++) mylist.push_back (i*10);

   std::list<int>::iterator it = mylist.begin();

   std::advance (it,9);

   std::cout << "The 9th element in mylist is: " << *it << '\n';

   return 0;
}

Let us compile and run the above program, this will produce the following result −

The 9th element in mylist is: 90
iterator.htm
Advertisements