Skip to content. Skip to navigation

ICTP Portal

Sections
You are here: Home Manuals on-line PGI Compiler pgC_lib advance
Personal tools
Document Actions

advance



Click on the banner to return to the class reference home page.

advance


Iterator Operation

Summary

Move an iterator forward or backward (if available) by a certain distance.

Data Type and Member Function Indexes
(exclusive of constructors and destructors)

None

Synopsis

#include <iterator>

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

Description

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. This function uses operator+ and operator- for random access iterators, which provides a constant time implementation. For input, forward, and bidirectional iterators, advance uses operator++ to provide linear time implementations. advance also uses operator-- with bidirectional iterators to provide 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.

Example

//
// advance.cpp
//
 #include<iterator>
 #include<list>
 #include<iostream.h>

 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;
 }

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

Warnings

If your compiler does not support default template parameters then you need to always supply the Allocator template argument. For instance you'll have to write:

vector<int,allocator<int> >

instead of:

vector<int>

See Also

Sequences, Random Access Iterators, distance


©Copyright 1996, Rogue Wave Software, Inc.


Powered by Plone This site conforms to the following standards: