Deleting values from a set

suggest change

The most obvious method, if you just want to reset your set/multiset to an empty one, is to use clear:

std::set<int> sut;
sut.insert(10);
sut.insert(15);
sut.insert(22);
sut.insert(3); 
sut.clear(); //size of sut is 0

Then the erase method can be used. It offers some possibilities looking somewhat equivalent to the insertion:

std::set<int> sut;
std::set<int>::iterator it;
          
sut.insert(10);
sut.insert(15);
sut.insert(22);
sut.insert(3); 
sut.insert(30);
sut.insert(33);
sut.insert(45);
    
// Basic deletion
sut.erase(3);
    
// Using iterator
it = sut.find(22);
sut.erase(it);
          
// Deleting a range of values
it = sut.find(33);
sut.erase(it, sut.end());
    
std::cout << std::endl << "Set under test contains:" << std::endl;
for (it = sut.begin(); it != sut.end(); ++it)
{
  std::cout << *it << std::endl;
}

Output will be:

Set under test contains:                                                                                                                                                                                                                                                                                                  
10                                                                                                                                                                                                                                                                                                                        
15                                                                                                                                                                                                                                                                                                                        
30

All those methods also apply to multiset. Please note that if you ask to delete an element from a multiset, and it is present multiple times, all the equivalent values will be deleted.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::set and std::multiset:
* Deleting values from a set

Table Of Contents
8 Arrays
11 Loops
28 std::set and std::multiset
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype