How to use a vector erase in C++

A vector is a dynamic array which is already implemented in the standard C++ library. This vector class has the ability to grow and shrink dynamically. The elements are placed in a contiguous fashion so that they can be traversed by iterators.

vector::erase()

The vector::erase() function is a function that is implemented in the vector class and used to remove elements one-by-one.This function erases the element from a desired position.

Syntax

  • erase( position )

  • erase( starting_position , ending_position )

These positions are the iterators.

svg viewer
svg viewer

Examples

  1. The code below is a sample using erase(position)
#include <iostream>
using namespace std;
// including vector library.
#include <vector>
// main function.
int main() {
// vector object.
vector < int > temp { 5, 4, 8, 9};
// iterator for temp.
vector<int> :: iterator it;
it = temp.begin();
// increments iterator so it
// points at index = 1
it++;
// printing temp before erasing
for(auto it = temp.begin(); it != temp.end() ; it++)
cout << *it << " ";
cout << "\n";
// erasing.
temp.erase(it);
// printing after erasing.
for(auto it = temp.begin(); it != temp.end() ; it++)
cout << *it << " ";
return 0;
}
  1. The code below is a sample using erase(starting_position , ending_position)
#include <iostream>
using namespace std;
// including vector library.
#include <vector>
// main function.
int main() {
// vector object.
vector < int > temp { 5, 4, 8, 9,7};
// iterator for temp.
vector<int> :: iterator starting_it, ending_it;
starting_it = temp.begin();
// increments iterator so it
// points at index = 1
starting_it++;
ending_it = temp.end();
// decrements iterator so it
// points at index = 4
ending_it--;
// printing temp before erasing
for(auto it = temp.begin(); it != temp.end() ; it++)
cout << *it << " ";
cout << "\n";
// erasing.
temp.erase(starting_it, ending_it);
// printing after erasing.
for(auto it = temp.begin(); it != temp.end() ; it++)
cout << *it << " ";
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved