Vector Remove nth Element C++

Vector Remove nth Element C++

std::vector is an STL template class (Standard Template Library) in C++. And it’s the default container we use. To delete the item with index n (nth item) from std::vector, there are several ways.

Using vector.erase

vector.erase removes a single element (position) or a range of elements ([first,last]) from the vector and reduces the container size.

iterator erase ( position );
iterator erase ( first, last );

Example

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> newvector{};

    // to define values for the vector
    for (int i=1; i<=20; i++) newvector.push_back(i);

    // to remove the 10th element
    newvector.erase (newvector.begin()+9);

    // to remove the 16th element 
    newvector.erase (newvector.begin()+15);

    // to remove the 8th element 
    newvector.erase (newvector.begin()+7);


    for (unsigned i=0; i<newvector.size(); ++i)
        std::cout << ' ' << newvector[i];
    std::cout << '\n';


    return 0;
}

Output

1 2 3 4 5 6 7 9 11 12 13 14 15 16 18 19 20

Using pList.erase

pList.erase(pList.begin()+i);

If the vector has fewer than i+1 elements, the compiler can’t decide the output.

About Post Author