advance() in C++

advance(): This function advances the iterator it by n element positions. 

Parameters: Two parameters are required for this function.

__it - Iterator to be advanced.

__n- Number of element positions to advance. 

The distance shall be a numerical type able to represent distances between iterators of this type.

Syntax:

advance(__it, __n)

For Example:

arr = {1,5,6,10,11}

it = arr.begin()

advance(it,2) = > It advance the iterator it by 2 positions. So it points to 6.

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> arr = {1561011};

    vector<int>::iterator it = arr.begin();

    //it moves the iterator 2 ponits away from
    //begin so it points to 6
    advance(it, 2);

    cout << *it << "\n";

    return 0;
}


No comments:

Post a Comment