共用方式為


advance (STL Samples)

說明如何使用前進距離 Visual C++ 標準樣板程式庫 (STL) 函式。

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

備註

注意事項注意事項

在原型中的類別/參數名稱不相符的標頭檔中的版本。某些已修改以提高可讀性。

前進距離 STL 函式會接受兩個參數:

  • 初始化 — 演進 iterator。

  • 分散式 — 為累加的 iterator 的項目數。

前進距離 STL 函式往前推進 iterator n 次。 如果 iterator 隨機存取 iterator 型別,函式會評估運算式為 「 iterator + = n。 否則,它會每個增量進行評估: + + iterator。 如果 iterator 是輸入或轉寄的 iterator 的型別, n 不可以是負數。

範例

// 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

需求

標頭: <iterator>

請參閱

概念

標準樣板程式庫範例