Share via


advance (STL Samples)

Illustrates how to use the advance Standard Template Library (STL) function in Visual C++.

template<class InIt, class Dist> 
   void advance( 
      InIt& it,  
      Dist n 
   );

Remarks

Note

The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.

The advance STL function accepts two parameters:

  • InIt — The iterator to advance.

  • Dist — The number of elements to increment the iterator by.

The advance STL function advances the iterator n times. If the iterator is a random-access iterator type, the function evaluates the expression as iterator += n. Otherwise, it performs each increment by evaluating: ++iterator. If the iterator is an input or forward iterator type, n must not be negative.

Example

// Advance.cpp
// compile with: /EHsc

#pragma warning (disable:4786)
#include <iostream>
#include <string>
#include <list>

using namespace std ;

typedef list<string> STRLIST;

int main() {
    STRLIST List;
    STRLIST::iterator iList;
    STRLIST::difference_type dTheDiff;

    List.push_back("A1");
    List.push_back("B2");
    List.push_back("C3");
    List.push_back("D4");
    List.push_back("E5");
    List.push_back("F6");
    List.push_back("G7");

    // Print out the list
    iList=List.begin();
    cout << "The list is: ";
    for (int i = 0; i < 7 ; i++, iList++)
        cout << *iList  << "  ";

    // Initialize to the first element"
    iList=List.begin();
    cout << "\n\nAdvance to the 3rd element." << endl;
    advance(iList,2);
    cout << "The element is " << *iList << endl;
    dTheDiff = distance( List.begin(), iList);
}

Output

The list is: A1  B2  C3  D4  E5  F6  G7  

Advance to the 3rd element.
The element is C3

Requirements

Header: <iterator>

See Also

Concepts

Standard Template Library Samples