This tutorial will discuss about unique ways to remove an element by value from a vector in C++.

Technique 1: Using STL Algorithm std::remove() and vector::erase()

To delete all occurrences of a given value from vector, we first call the std::remove() function to shift all the matched values to the end of vector. It returns an iterator pointing to new virtual end of vector i.e. after that there will be only the elements that we need to delete. Then pass that iterator to vector::erase() to delete all those elements till the end of vector. This way it will remove all occurrences of a given value from the vector.

Let’s see the complete example,

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    // Vector of integers
    std::vector<int> vecObj {11, 12, 13, 14, 15, 16, 12, 43, 12};

    // Value to be deleted
    int value = 12;

    // Remove all occurrences of element
    // with given value from vector
    vecObj.erase(
            std::remove(
                vecObj.begin(),
                vecObj.end(),
                value),
            vecObj.end());

    // print all elements of vector
    for(auto elem : vecObj) {
        std::cout<<elem << ", ";
    }

    return 0;
}

Output :

11, 13, 14, 15, 16, 43,

Technique 2: Using vector::erase() and while loop

Iterate through all elements of vector using a while loop and an iterator. During iteration, for each value check if it matches with the given value then delete it using the vector::erase() function. This way it will delete all occurrences of given value from the vector.

Let’s see the complete example,

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    // Vector of integers
    std::vector<int> vecObj {11, 12, 13, 14, 15, 16, 12, 43, 12};

    // Value to be deleted
    int value = 12;


    auto it = vecObj.begin();

    // Iterate over all elements of vector
    while ( it != vecObj.end())
    {
        // If element matches the element to be deleted
        // then delete it
        if (*it == value)
        {
            it = vecObj.erase(it);
        }
        else
        {
            it++;
        }
    }

    // print all elements of vector
    for(auto elem : vecObj)
    {
        std::cout<<elem << ", ";
    }
    std::cout<<std::endl;

    return 0;
}

Output :

11, 13, 14, 15, 16, 43,

Summary

Today we learned about several ways to remove an element by value from a vector in C++. Thanks.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.