Erasing Elements from a Vector in C++

Erasing Elements from a Vector in C++

4 mins read7.8K Views Comment
Updated on Jul 10, 2024 20:28 IST

Vector in C++ is a useful tool for handling and organizing large sets of data. Vectors are simple to utilize and provide a lot of functionality.

2023_01_MicrosoftTeams-image-263.jpg

One of the main advantages of using vector in C++ is that they provide an easy way to add and remove elements. This article will cover the methods for removing elements from a vector container. So, without further ado, let’s get started! 

We will be covering the following sections: 

Methods to Erase Elements from C++ Vectors 

There are three straightforward methods to delete elements from a C++ vector: 

  • vector::pop_back() 
  • vector::erase() 
  • vector::clear() 

But before diving into these methods, let’s brush up on our vector basics! 

Crack the code of C/C++ with our comprehensive guide; find details on top colleges, programmes and online courses.

You can also explore: Multilevel inheritance in C++ with real life analogy

C++ Vectors are a container class type, meaning they can hold a collection of objects. They are implemented as an array, but with dynamic sizing, so they can grow or shrink as needed. This makes vectors a great choice for situations where the number of elements may change during the course of a program. 

A vector is declared using the keyword vector followed by the data type that the vector will store, in angular brackets <>.  

For example, to create a vector of integers, you would use the following syntax: 

vector<int> newVector; 

A vector can also be initialized with a specific set of values by providing a list of elements to its constructor. For example: 

vector<int> newVector {5, 4, 3, 1, 2}; 

vector::pop_back() 

The vector::pop_back() method can be used to remove elements stored in a vector. It decreases the size of the container by one and eliminates the element from the end of the vector. 

You can also explore: Understanding Copy Constructor in C++

The syntax is given below: 

vector.pop_back() 
  • Parameters: None 
  • Return value: None 

Let’s take a look at an example: 


 
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
v.push_back(3); //Insert element 3
v.push_back(5); //Insert element 5
v.push_back(7); //Insert element 7
//vector(v) has 3 elements with size 3
v.pop_back(); //This method will remove the last element
for(int i=0;i<v.size();i++){
cout << v[i] << " ";
}
return 0;
}
Copy code

Output: 

2023_01_image-147.jpg

Explanation: 

Note that we used the vector::push_back() method to insert elements into a vector. Insertion always happens at the end. 

You can also explore: Ceil function in C++

When the function pop_back() is called, always the last element is removed. The destructor of the object is called and the length of the vector is decreased by 1. 

Time Complexity: 

Inserting an element at the end of a vector in C++ may take linear time as it may require the array to be expanded. Removing the last element, however, only takes constant time as it does not involve any resizing of the array. 

Time complexity is constant, that is, O(1)

vector::erase() 

The vector::erase() method can remove either a single element from a specific position or a range of elements [first,last). This function decreases the container size by the number of elements removed, and the removed elements are eliminated. 

Keep in mind that, as vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions.  

You can also explore: Convert char to int in C++ Using Different Methods

This operation can be less efficient than the same operation performed by other types of sequence containers such as lists.  

Syntax: 

vector.erase(position) 
// or 
vector.erase(left,right)    //([left,right)) 

Parameters:

  • position:  Iterator pointing to a single element to be removed from the vector. 
  • first, last: This range includes all elements between first and last, including the element, pointed to by first, but not the element pointed to by last. 

Return value:

The vector class provides a method that returns an iterator pointing to the new location of the element that followed the last element erased by the function call. This returned iterator will be the end of the container if the operation erased the last element in the sequence. 

Let’s take a look at an example: 


 
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
//Insert values 0 to 5
for(int i=0;i<=5;i++)
v.push_back(i);
//vector has [0,1,2,3,4,5]
//erase the 5th element
v.erase(v.begin()+4);
//erase first 3 elements
v.erase(v.begin(),v.begin()+3);
for(int i=0;i<v.size();i++){
cout << v[i] << " ";
}
return 0;
}
Copy code

Output: 

2023_01_image-148.jpg

Time Complexity: 

Linear on the number of elements erased (destructions) plus the number of elements after the last element erased (moving). 

Best case: O(1)

Worst case: O(n)

vector::clear() 

The vector::clear() method can be used to remove all elements from the container, leaving it with a size of 0. 

The syntax is given below: 

vector.clear() 
  • Parameters: None 
  • Return value: None 

Let’s take a look at an example: 


 
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
v.push_back(5); //Insert element 5
v.push_back(10); //Insert element 10
//Empty the vector
v.clear();
v.push_back(11); //Insert element 11
v.push_back(12); //Insert element 12
//In the end, the vector contains elements 11 and 12
for(int i=0;i<v.size();i++){
cout << v[i] << " ";
}
return 0;
}
Copy code

Output: 

2023_01_image-153.jpg

Time Complexity: 

Space complexity, that is, O(n).

Difference between clear() and erase() 

The vector::clear() method removes all elements from the vector, reducing its size to 0.  

The vector::erase() method is used to remove specific elements or a range of elements from the vector. 

You can also expore: Member function in C++

Endnotes 

In conclusion, the vector class provides several methods to remove elements from the container such as: 

  • pop_back() to remove the last element, 
  • erase() to remove specific elements or range of elements,  
  • clear() to remove all elements and leave the container with a size of 0.  
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio