
Iterator Operation
Moves an iterator forward or backward (if available) by a certain distance.
None
#include <iterator> template <class InputIterator, class Distance> void advance (InputIterator& i, Distance n);
The advance template function allows an iterator to be advanced through a container by some arbitrary distance. For bidirectional and random access iterators, this distance may be negative. For random access iterators, this function uses operator+ and operator- for constant time implementations. For input, forward, and bidirectional iterators, advance uses operator++ for linear time implementations. advance also uses operator-- with bidirectional iterators for linear time implementations of negative distances.
If n is positive, advance increments iterator reference i by n. For negative n, advance decrements reference i. Remember that advance accepts a negative argument n for random access and bidirectional iterators only.
//
// advance.cpp
//
#include<iterator>
#include<list>
#include<iostream>
using namespace std;
int main()
{
//
//Initialize a list using an array
//
int arr[6] = {3,4,5,6,7,8};
list<int> l(arr,arr+6);
//
//Declare a list iterator, s.b. a ForwardIterator
//
list<int>::iterator itr = l.begin();
//
//Output the original list
//
cout << "For the list: ";
copy(l.begin(),l.end(),
ostream_iterator<int,char>(cout," "));
cout << endl << endl;
cout << "When the iterator is initialized to l.begin(),"
<< endl << "it points to " << *itr << endl << endl;
//
// operator+ is not available for a ForwardIterator,
// so use advance.
//
advance(itr, 4);
cout << "After advance(itr,4), the iterator points to "
<< *itr << endl;
return 0;
}
Program Output :
For the list: 3 4 5 6 7 8 When the iterator is initialized to l.begin(), it points to 3 After advance(itr,4), the iterator points to 7
If your compiler does not support default template parameters, then you always need to supply the Allocator template argument. For instance, you have to write:
vector<int,allocator<int> >
instead of:
vector<int>
If your compiler does not support namespaces, then you do not need the using declaration for std.
Sequences, Random Access Iterators, distance