Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL Set Erase by Value

Tags:

c++

set

stl

I want to remove an element from std::set.

I am aware that the best and straightforward practice is to check its existence in the set using set<T>::find(T val) method, and then erase it using the returned set<T>::iterator. But I wish to use the shorthand method of erasing by value.

Even though std::set does provide that through the overloaded function set<T>::erase(T val) to erase by value as listed here, I couldn't find what happens if the value does not exist in the set.

As one would intuitively expect, does it do nothing if the argument value does not exist in the set? Is it guaranteed that it won't throw any error/exception?

like image 989
dyno8426 Avatar asked Jan 16 '20 08:01

dyno8426


People also ask

How do I remove a specific element from a set?

The remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.

How does set erase work?

std::set::erase. Removes from the set container either a single element or a range of elements ([first,last)). This effectively reduces the container size by the number of elements removed, which are destroyed.

How do I remove a value from a set in CPP?

Deleting a single element from the set container is very simple in C++. The idea is to pass the given element to the set::erase function, which erases it from the set.

How do you remove the first element of a set?

set::erase() erase() function is used to remove elements from a container from the specified position or range.


1 Answers

std::set abides by associative container requirements of 26.2.6 associative.reqmts.

It returns the number of actual erased elements, which for std::set must be zero or one, dependent on existence. Per 26.2.6.1 associative.reqmts.except, it is only guaranteed not to throw if the container comparator (which can be customized, obviously) does not throw when used during the search.

like image 159
WhozCraig Avatar answered Nov 04 '22 17:11

WhozCraig