Skip to content
Related Articles

Related Articles

Improve Article

std::advance in C++

  • Difficulty Level : Easy
  • Last Updated : 02 Aug, 2017
Geek Week

std::advance advances the iterator ‘it’ by n element positions.

Syntax :

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.

Return type :
None.

Motivation problem : A vector container is given. Task is to print alternate elements.

Examples :

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);
    }
}

Output:

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

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :