In C++, the set class offers various methods to delete its elements. One of these methods is erase(), which allows users to remove specific elements from a set. In this article, we will explore the different overloaded versions of this function.

A set in C++ is a container that stores unique elements in a specific order. This means that each value can only appear once in a set. When we try to erase an element from a set, two situations can arise:

  1. The value exists in the set.
  2. The value doesn’t exist in the set.

We will also learn how to handle both the scenarios gracefully.

Remove an Element from Set using the erase() function

To remove a specific value from a set, we can use one of the overloaded implementations of the erase() function. The overloaded version of erase() function takes the value we wish to remove as its argument i.e.

size_type erase (const value_type& val);

If the specified value is present in the set, the function removes it; otherwise, it does nothing.

The erase() function returns the number of elements that were successfully removed. For a set, this will always be either 0 or 1 since a specific value can only exist once (or not at all) in a set.

Let’s see this in action with the complete code example.

#include <iostream>
#include <set>

int main()
{
    std::set<int> setObj = {15, 22, 11, 23, 73};

    int valueToRemove = 14;

    // Remove element with value 14 from the Set
    size_t elementsRemoved = setObj.erase(valueToRemove);

    if (elementsRemoved)
    {
        std::cout << "Value " << valueToRemove << " was removed from the set." << std::endl;
    }
    else
    {
        std::cout << "Value " << valueToRemove << " was not found in the set." << std::endl;
    }

    valueToRemove = 11;
    // Remove element with value 11 from the Set
    elementsRemoved = setObj.erase(valueToRemove);

    if (elementsRemoved)
    {
        std::cout << "Value " << valueToRemove << " was removed from the set." << std::endl;
    }
    else
    {
        std::cout << "Value " << valueToRemove << " was not found in the set." << std::endl;
    }

    return 0;
}

Output:

Value 14 was not found in the set.
Value 11 was removed from the set.

In the above code, we first attempt to remove the value 14 from our set. Since 14 is not in the set, the program will output that it was not found. Next, we try to remove the value 11. This time, since 11 is present, it will be removed, and the program will confirm its removal.

This overloaded implementation of erase() function provides a straightforward way to remove elements from a C++ set by value.

Removing Elements from a Set Based on Position in C++

The set container in C++ stores elements in a sorted order. Sometimes, you might want to remove elements based on their position rather than their value. To achieve this, we use iterators, as set doesn’t support random access operations like arrays. We will use this overloaded version of erase() function,

iterator  erase (const_iterator position);

Steps to Remove an Element by Position from a Set:

  1. Get an iterator pointing to the first element using the begin() function of the set.
  2. Increment the iterator the required number of times to point to the desired position.
  3. Pass this iterator to the erase() function to remove the element.

Let’s see this with an example where we remove the 3rd element from a set.

#include <iostream>
#include <set>

int main()
{
    std::set<int> setObj = {5, 15, 25, 35, 44};

    // Remove the 3rd element, so we need an iterator pointing there
    // Step 1: get iterator pointing to first element of set
    std::set<int>::iterator it = setObj.begin();

    // Step 2: Move iterator to the 3rd position
    std::advance(it, 2);

    // Remove the 3rd element
    setObj.erase(it);

    // Display the set after removal
    for (int value : setObj)
    {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

5 15 35 44 

In the code above, the advance() function moves the iterator to the 3rd position, which holds the value 22. The erase() function then removes this element. After the operation, the program outputs the modified set.

This implementation of erase() function returns an iterator pointing to the next element after the erased one (or the end() iterator if the last element was erased).

Removing a Range of Elements from a Set in C++

In C++, the set container provides another implementation of the erase() function that not only allows you to remove a single element but also a range of elements. To erase a range, two iterators are passed to the erase() function: one pointing to the beginning of the range and the other pointing just past the end of the range.

We will use this overloaded version of erase() function,

iterator  erase (const_iterator first, const_iterator last);

Steps to Remove a Range of Elements:

  1. Obtain an iterator to the start of the range.
  2. Obtain another iterator to the end of the range.
  3. Call the erase() function with both iterators as arguments.

Let’s demonstrate this with an example where we remove the first three elements from a set.

#include <iostream>
#include <set>

int main()
{
    std::set<int> setObj = {5, 15, 25, 35, 44};

    // Fetch Iterators for the start and end of the range to be erased
    std::set<int>::iterator it1 = setObj.begin();
    std::set<int>::iterator it2 = setObj.begin();

    std::advance(it2, 3); // Pointing just after the third element

    // Remove the range [it1, it2)
    setObj.erase(it1, it2);

    // Display the set after removal
    for (int value : setObj)
    {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

35 44

In the above code, the advance() function moves the it2 just after the third element. The erase() function then removes elements from the start of the set up to, but not including, the third element. The output of the program will be the modified set with the first three elements removed.

By using the erase() function with range iterators, you can efficiently remove multiple contiguous elements from a set in C++. This implementation of erase() function returns an iterator to the element that follows the last element removed (or the end() iterator if the last element was erased).

Summary

In this tutorial, we learned about three different ways to remove elements from a Set in C++.

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.