Open In App

std::advance in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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

CPP




// 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

C++




#include <iostream>
#include<bits/stdc++.h>
using namespace std;
 
int main() {
 
    vector<int >vect(10);
  //insert the ten element in the vector
    for(int i=1;i<=10;i++)
    {
      vect[i-1]=i;
    }
    //iterator pointing to first element.
    vector<int >::iterator it=vect.begin();
   
     for(int i=1;i<=10;i++)
     {
       cout<<*it<<" ";
       it++;
        
     }
   vector<int >::iterator it1=vect.begin();
  //here it is pointing to the 3rd element.  
    advance(it1,2);//here second argument is the index base.
     
  cout<<endl;
   
  cout<<*it1;
  //print it1 pointing to the 3rd position.
    return 0;
}
/* This code is contributed by Sameer Hake/*


Output

1 2 3 4 5 6 7 8 9 10 
3


Last Updated : 26 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads