Set Erase Function - C++ Programming Tutorial
C++ Course / STL Set & Map / Set Erase Function

Set Erase Function

BLUF: Mastering Set Erase Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Set Erase Function

C++ is renowned for its efficiency. Learn how Set Erase Function enables low-level control and high-performance computing in the tutorial below.

C++ set erase

The erase function in C++ for sets is employed to eliminate either a specific element linked to a provided key or a selection of elements ([first, last)) from the set container. Consequently, the size of the set will decrease by the count of elements that have been deleted.

Syntax

Example

void erase (iterator position);                       	  //until C++ 11

size_type erase (const value_type& val);    		  //until C++ 11

void erase (iterator first, iterator last);  		  //until C++ 11

iterator  erase (const_iterator position);		  //since C++ 11

size_type erase (const value_type& val);		  //since C++ 11	

iterator  erase (const_iterator first, const_iterator last); //since C++ 11

Parameter

position: iterator indicating a specific element to be deleted from the set.

val : Value to be removed from the set.

first : Beginning of the range to erase.

last : End of the range to erase.

Return value

It returns an iterator pointing to the next element after the deleted element or returns the count of deleted elements.

Complexity

erase(position) : Amortized constant.

erase (val) : Logarithmic in container size.

Delete(first,last): Time complexity is proportional to the distance between the first and last elements in the sequence.

Iterator validity

Iterators, references, and pointers pointing to elements affected by the function become invalid.

All remaining iterators, pointers, and references retain their validity.

Data Races

The container is modified.

The removed components have been altered. It is considered unsafe to iterate over ranges within the container, but accessing other elements concurrently is deemed safe.

Exception Safety

This function does not throw exception.

If an incorrect range or position is provided, it leads to unpredictable behavior.

Example 1

Let's examine a basic example of removing an element using an iterator.

Example

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  set<int> myset;
  set<int>::iterator it;

  myset = {10,20,30};
  
  cout<<"Before erasing the element: \n";
   for (it=myset.begin(); it!=myset.end(); ++it)
    cout << *it << '\n';

  it=myset.find('b');
  myset.erase (*it);                   // erasing by iterator

  cout<<"\nAfter erasing the element: \n";
  for (it=myset.begin(); it!=myset.end(); ++it)
    cout << *it << '\n';
    
  return 0;
}

Output:

Output

Before erasing the element: 
10
20
30

After erasing the element: 
10
20
30

In the previous example, the term "element" is replaced by the iterator "it".

Example 2

Let's explore a basic example of removing an item from a set using the specified key value:

Example

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  set<int> myset;
  set<int>::iterator it;

  myset = {10, 20, 30, 40};
  
  cout<<"Before erasing the element: \n";
   for (it=myset.begin(); it!=myset.end(); ++it)
    cout << *it<< '\n';

   myset.erase (30);                  // erasing by value

  cout<<"\nAfter erasing the element: \n";
  for (it=myset.begin(); it!=myset.end(); ++it)
    cout << *it<< '\n';
  return 0;
}

Output:

Output

Before erasing the element: 
10
20
30
40

After erasing the element: 
10
20
40

In the previous example, the erase(value) method removes the value 30 from the set.

Example 3

Let's examine a basic example demonstrating how to delete an element within a specified range:

Example

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  set<int> myset;
  set<int>::iterator it;

  myset = {10, 20, 30};
  
  cout<<"Before erasing the element are: \n";
   cout<<"Size is: "<<myset.size()<<'\n';
   for (it=myset.begin(); it!=myset.end(); ++it)
   cout << *it << '\n';

   myset.erase ( myset.begin () ,  myset.end () );   // erasing by range

  cout<<"\nAfter erasing the element are: \n";
  cout<<"Size is: "<<myset.size();
  for (it=myset.begin(); it!=myset.end(); ++it)
  cout << *it << '\n';
  return 0;
}

Output:

Output

Before erasing the element are: 
Size is: 3
10
20
30

After erasing the element are: 
Size is: 0

The erase(first, last) function is employed to remove the element within the specified range, from the beginning to the end.

Example 4

Let's examine a basic example demonstrating the removal of all odd numbers from a given set:

Example

#include <set>
#include <iostream>

using namespace std;

int main()
{
    set<int> m = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
                          
    // erase all odd numbers from m
    cout<<"After erasing odd numbers,elements are:\n ";
    for(auto it = m.begin(); it != m.end(); )
        if(*it % 2 == 1)
            it = m.erase(it);
        else
            ++it;
    for(auto& p : m)
        cout << p << ", ";
}

Output:

Output

After erasing odd numbers, elements are:
 2, 4, 6, 8, 10, 12, 14,

In the above instance, the odd numbers have been removed and only the even numbers are shown.

Example 5

Let's see another example:

Example

#include <set>  
#include <string>  
#include <iostream>  
#include <iterator> // next() and prev() helper functions  
  
using namespace std;  
  
using myset = set<string>;  
  
void printset(const myset& s) {  
    for (const auto& iter : s) {  
        cout << " [" << iter << "]";  
    }  
    cout << endl << "size() == " << s.size() << endl << endl;  
}  
  
int main()  
{  
    myset s1;  
  
    // Fill in some data to test with, one at a time  
    s1.insert("Bob");  
    s1.insert("Robert");  
    s1.insert("Bert");  
    s1.insert("Rob");  
    s1.insert("Bobby");  
  
    cout << "Starting data of set s1 is:" << endl;  
    printset(s1);  
    // The 1st member function removes an element at a given position  
    s1.erase(next(s1.begin()));  
    cout << "After the 2nd element is deleted, the set s1 is:" << endl;  
    printset(s1);  
  
    // Fill in some data to test with, one at a time, using an intializer list  
    myset s2{ "meow", "hiss", "purr", "growl", "yowl" };  
  
    cout << "Starting data of set s2 is:" << endl;  
    printset(s2);  
    // The 2nd member function removes elements  
    // in the range [First, Last)  
    s2.erase(next(s2.begin()), prev(s2.end()));  
    cout << "After the middle elements are deleted, the set s2 is:" << endl;  
    printset(s2);  
  
    myset s3;  
  
    // Fill in some data to test with, one at a time, using emplace  
    s3.emplace("C");  
    s3.emplace("C#");  
    s3.emplace("D");  
    s3.emplace("D#");  
    s3.emplace("E");  
    s3.emplace("E#");  
    s3.emplace("F");  
    s3.emplace("F#");  
    s3.emplace("G");  
    s3.emplace("G#");  
    s3.emplace("A");  
    s3.emplace("A#");  
    s3.emplace("B");  
  
    cout << "Starting data of set s3 is:" << endl;  
    printset(s3);  
    // The 3rd member function removes elements with a given Key  
    myset::size_type count = s3.erase("E#");  
    // The 3rd member function also returns the number of elements removed  
    cout << "The number of elements removed from s3 is: " << count << "." << endl;  
    cout << "After the element with a key of \"E#\" is deleted, the set s3 is:" << endl;  
    printset(s3);  
}

Output:

Output

Starting data of set s1 is:
 [Bert] [Bob] [Bobby] [Rob] [Robert]
size() == 5

After the 2nd element is deleted, the set s1 is:
 [Bert] [Bobby] [Rob] [Robert]
size() == 4

Starting data of set s2 is:
 [growl] [hiss] [meow] [purr] [yowl]
size() == 5

After the middle elements are deleted, the set s2 is:
 [growl] [yowl]
size() == 2

Starting data of set s3 is:
 [A] [A#] [B] [C] [C#] [D] [D#] [E] [E#] [F] [F#] [G] [G#]
size() == 13

The number of elements removed from s3 is: 1.
After the element with a key of "E#" is deleted, the set s3 is:
 [A] [A#] [B] [C] [C#] [D] [D#] [E] [F] [F#] [G] [G#]
size() == 12

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience