Library: Iterators
Function
A function that advances an iterator forward or backward (if available) by a certain distance
#include <iterator>
namespace std {
template <class InputIterator, class Distance>
void advance(InputIterator& i, Distance n);
}
The advance() function template 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> // for advance
#include <iostream> // for cout, endl
#include <list> // for list
int main ()
{
// Typedefs for convenience.
typedef std::list<long, std::allocator<long> > list;
typedef std::ostream_iterator<list::value_type, char,
std::char_traits<char> > os_iter;
// Initialize a list using an array.
const list::value_type arr [] = { 3, 4, 5, 6, 7, 8 };
list l (arr + 0, arr + sizeof arr / sizeof *arr);
// Declare a list iterator, s.b. a ForwardIterator.
list::iterator itr = l.begin ();
// Output the original list.
std::cout << "For the list: ";
std::copy (l.begin (), l.end (), os_iter (std::cout, " "));
std::cout << std::endl << std::endl
<< "When the iterator is initialized to l.begin (),"
<< "\nit points to " << *itr << std::endl;
// operator+ is not available for a ForwardIterator,
// so use advance.
std::advance (itr, 4);
std::cout
<< "\nAfter advance (itr, 4), the iterator points to "
<< *itr << std::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
Sequences, Random Access Iterators, distance()
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 24.3.4