当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。