×

Search anything:

Different ways to remove elements from vector in C++ STL

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 30 minutes | Coding time: 10 minutes

In this article, we will go through multiple ways to delete elements from a vector container in C++ Standard Template Library (STL). Methods used to remove elements from vector are:

  • vector::pop_back()
  • vector::pop_front()
  • vector::erase()
  • vector::clear()
  • remove(first,last,val)
  • remove_if()
  • remove_copy(first,last,result,val)

Before going into it, we will go through a quick review of vector basics.

Vectors are same as dynamic arrays with the ability to resize itself automatically while insertion and deletion. Vectors are placed in contiguous storage so that they can be accessed and traversed using iterators.

Defining a vector:

vector<int> v;

vector::push_back() is used to insert elements into a vector.Insertion happens at the end.

Insertion at the end takes linear time, as sometimes there may be a need of extending the array.
Removing the last element takes constant time because no resizing happens.
Inserting or removing element in the middle is linear in time.

Functions to be known:

  1. vector.size() Returns the number of elements in vector.
  2. vector.begin() Returns an iterator pointing to the first element in vector.
  3. vector.end() Returns an iterator pointing to the theoretical element that follows the last element in the vector.
  4. vector.push_back(val) Push element (val) into the vector from back.
  5. vector.empty() Returns whether vector is empty.

We will now get started with the different methods to remove elements from a vector.

vector::pop_back()

vector::pop_back() method is used to remove elements stored inside a vector.
It reduces the container size by one and destroys the removed element.

Syntax:

vector.pop_back()
  • Parameters: None
  • Return value: None
#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> v;
    v.push_back(1);//Insert element 1.
    v.push_back(2);//Insert element 2.

    //Now the vector(v) has 2 elements in it, with size 2

    v.pop_back();//This method will remove the last element

    for(int i=0;i<v.size();i++){
        cout << v[i] << " ";
    }
    //Prints [1]
    return 0;
}

Errors and Exceptions:
1.No-Throw-Guarantee: If an exception is thrown, there is no change in the container.
2.If vector is empty, it shows undefined behavior.

Does pop_back() removes values along with elements?
When this function is called, element at the last is removed. The destructor of the object is called and length of vector is decreased by 1.

Time Complexity: O(1) or (constant)

vector::pop_front()

This is similar to pop_back() but removes elements from the front instead of back.

Syntax:

vector.pop_front()

Complete example:

#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> v;
    v.push_back(1);//Insert element 1.
    v.push_back(2);//Insert element 2.

    //Now the vector(v) has 2 elements in it, with size 2

    v.pop_front(); // This method will remove the first element

    for(int i=0;i<v.size();i++){
        cout << v[i] << " ";
    }
    //Prints [1]
    return 0;
}

vector::erase()

Removes either a single element or a range of elements.

Syntax:

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

Parameters: Position of the element or range of elements to be removed.
Result: Elements are removed from the position specified.
Time Complexity: O(N) - worst case, O(1) - best case

#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> v;
    //Insert values 1 to 10
    for(int i=1;i<=10;i++)
        v.push_back(i);
    //vector has [1,2,3,4,5,6,7,8,9,10]

    //erase the 7th element
    v.erase(v.begin()+6);

    //erase first 3 elements
    v.erase(v.begin(),v.begin()+3);

    for(int i=0;i<v.size();i++){
        cout << v[i] << " ";
    }
    //Prints [4 5 6 8 9 10]
    return 0;
}

vector::clear()

This method removes all elements from container, leaving with size 0.

Syntax:

vector.clear()

Parameters: No Parameters
Return: All elements of the vector are destroyed
Time Complexity: O(N)

#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> v;
    v.push_back(50);//Insert 50
    v.push_back(100);//Insert 100
    //Empty the vector
    v.clear();

    v.push_back(101);//Insert 101

    //Finally, the vector contains 101.               
    return 0;
}

Difference between clear() and erase():
clear() removes all elements from vector and reducing it to size 0.
erase() is used to remove specific elements from vector.

remove(first,last,val)

This method removes all elements which are equal to val and returns an iterator to the new end of that range.
Syntax:

remove(v.begin(),v.end(),val)

Parameters:

  • first,last: The range is used which contains all elements between first and last includeing first but not last.
  • val: Value to be removed.

Result: An iterator to the element that follows the last element not removed.

#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> v;
    //Insert values 1 to 10
    v.push_back(20);
    v.push_back(10);
    v.push_back(30);
    v.push_back(20);
    v.push_back(40);
    v.push_back(20);
    v.push_back(10);

    vector<int>::iterator new_end;
    new_end = remove(v.begin(), v.end(), 20);

    for(int i=0;i<v.size(); i++){
        cout << v[i] << " ";
    }
    //Prints [10 30 40 10]
    return 0;
}

Difference between remove() and erase()?

  1. erase() causes large amount of copies while remove() just does a logical delete and leaves vector unchanged by moving element around.

  2. If you need to remove multiple elements, remove() will copy elements only once to its final position while erase() would do this multiple times.

  3. erase() works best with elements in a position, remove() is best while working with range of elements.

remove_if()

Transforms the range [first,last) into a range with all elements for which func returns true removed.

Syntax:

remove_if(vector.begin(), vector.end(), func)

Parameters:
ForwardIterator first,last
UnaryPredicate func: This function accepts an element in the range as argument, and returns a value convertible to bool. If true, remove element.

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

bool isEven(int k){
    return ((i%2) == 0);
}

int main(){

    vector<int> v {1,2,3,4,5,6,7,8,9,10};
    //Initially the vector contains elements from 1 to 10.
    vector<int>::iterator it;
    it = remove_if(v.begin(), v.end(), isEven);
    //isEven() method checks each element whether it is even or not.

    for(int i=0;i<v.size(); i++){
        cout << v[i] << " ";
    }
    //Print the elements in vector
    //[1,3,5,7,9]

    return 0;
}

remove_copy(first,last,result,val)

Copies the elements in the range of vector to another vector except those that equal the value specified.

Syntax:

remove_copy(vector1.begin(),vector1.end(),vector2.begin(),val)

Parameters:

ForwardIterator first, last:
OutputIterator result
val: The value that needs to be removed.

#include <bits/stdc++.h>

using namespace std;

int main()
{
    vector<int> v1 {10,20,10,30,20,20,30,10};
    vector<int> v2(8);
    remove_copy(v1.begin(), v1.end(), v2.begin(), 20);

    for(int i=0;i<v2.size();i++){
        cout << v2[i] << " ";
    }
    //Prints[10,10,30,30,10,0,0,0]
    return 0;
}

With this, you have the complete knowledge of different ways to remove elements from C++ STL vector container.

Different ways to remove elements from vector in C++ STL
Share this