function template
<iterator>

std::advance

template <class InputIterator, class Distance>  void advance (InputIterator& it, Distance n);
前進迭代器
將迭代器it推進n個元素位置。

如果it隨機訪問迭代器,則該函式僅使用一次operator+operator-。否則,該函式會重複使用遞增或遞減運算子(operator++operator--),直到推進n個元素為止。

引數

it
要推進的迭代器。
InputIterator 至少應是輸入迭代器
n
要推進的元素位置數。
對於隨機訪問雙向迭代器,此值才可以為負。
Distance 應為一種數值型別,能夠表示此型別迭代器之間的距離。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// advance example
#include <iostream>     // std::cout
#include <iterator>     // std::advance
#include <list>         // std::list

int main () {
  std::list<int> mylist;
  for (int i=0; i<10; i++) mylist.push_back (i*10);

  std::list<int>::iterator it = mylist.begin();

  std::advance (it,5);

  std::cout << "The sixth element in mylist is: " << *it << '\n';

  return 0;
}

輸出

The sixth element in mylist is: 50


複雜度

隨機訪問迭代器 的常量。
否則,線性複雜度為 n

迭代器有效性

推進一個不是至少前向迭代器輸入迭代器可能會使從其值獲得的任何迭代器、指標和引用失效。

資料競爭

該函式修改迭代器,但從不進行解引用(呼叫不會訪問任何指向的物件)。
另請注意上面描述的對迭代器有效性的影響。

異常安全

如果對迭代器執行的任何算術運算丟擲異常,則此函式將丟擲異常,並提供與這些運算相同的保證級別。

另見