Related Articles

Related Articles

std::advance in C++
  • Difficulty Level : Easy
  • Last Updated : 02 Aug, 2017

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
filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :