vector erase() in C++

erase(): It is a build-in function in STL. It is used to remove element at given position from the

vector. 

It returns an iterator pointing to the next element (or end()) of the given vector.

This function will erase the element at the given position and thus shorten the vector by one. 

Note: This operation could be expensive.

Parameters

position: Iterator pointing to element to be erased.

Syntax:

vecName.erase(position)

For Example:

vec = {1,2,3,4}

vec.erase(vec.begin()) = > It removes 1 from the vector.

So , vector becomes {2,3,4}

Approach

C++

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

int main()
{
    vector<intvec = {1234};

    vec.erase(vec.begin());

    for (int i = 0i < vec.size(); i++)
        cout << vec[i] << " ";

    return 0;
}


No comments:

Post a Comment