dyno8426
dyno8426

Reputation: 1249

C++ STL Set Erase by Value

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?

Upvotes: 8

Views: 6361

Answers (2)

WhozCraig
WhozCraig

Reputation: 66254

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.

Upvotes: 7

Sreeraj Chundayil
Sreeraj Chundayil

Reputation: 5879

From cplusplus

(1) void erase (iterator position);

(2) size_type erase (const value_type& val);

(3) void erase (iterator first, iterator last);

Return value

For the value-based version (2), the function returns the number of elements erased.

Member type size_type is an unsigned integral type


So it returns 0 if no elements are erased.

Upvotes: 5

Related Questions