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. erase(key) deletes every equivalent element. erase(iterator) deletes only the one element that iterator refers to.

Feedback about page:

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



Table Of Contents