當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std::advance用法及代碼示例

std::advance將迭代器“ it”前進n個元素位置。

用法:

template 
    void advance (InputIterator& it, Distance n);

it: Iterator to be advanced
n: Number of element positions to advance.
This shall only be negative for random-access and bidirectional iterators.

返回類型:
None.

動機問題:給出了一個向量容器。任務是打印備用元素。


例子:

Input:10 40 20 50 80 70
Output:10 20 80
// C++ program to illustrate 
// using std::advance 
#include <bits/stdc++.h> 
  
// Driver code 
int main() 
{ 
    // Vector container 
    std::vector<int> vec; 
  
    // Initialising vector 
    for (int i = 0; i < 10; i++) 
        vec.push_back(i * 10); 
  
    // Printing the vector elements 
    for (int i = 0; i < 10; i++) { 
        std::cout << vec[i] << " "; 
    } 
  
    std::cout << std::endl; 
  
    // Declaring the vector iterator 
    std::vector<int>::iterator it = vec.begin(); 
  
    // Printing alternate elements 
    while (it < vec.end()) { 
        std::cout << *it << " "; 
        std::advance(it, 2); 
    } 
}

輸出:

0 10 20 30 40 50 60 70 80 90 
0 20 40 60 80


相關用法


注:本文由純淨天空篩選整理自 std::advance in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。