Why `std::unordered_map::erase(key_type const&)` return number of removed elements?

Viewed 152

Recently I went to use std::unordered_map::erase, and see the function has some overloads:

iterator erase( const_iterator pos );                         (1)  (since C++11)
iterator erase( iterator pos );                               (1)  (since C++17)
iterator erase( const_iterator first, const_iterator last );  (2)  (since C++11)
size_type erase( const key_type& key );                       (3)  (since C++11)

And in the description of the functions return value mentioned:

Return value
1-2) Iterator following the last removed element.
3) Number of elements removed.

The last one (3), saying we could have the number of removed elements. Does that mean it's possible to have the same keys on the map?

1 Answers

Because there is also unordered_multimap where several elements can have the same key. Returning the number of erased elements makes perfect sense for multimap, multiset, unordered_multimap and unordered_multiset. The returning of the number of elements rather than just bool for the non-multi containers is a way to make the common "interface" of map and multimap (etc) as close to each other as possible so that in some situations either can be used via a template parameter. Erase for a non-multi map or set (or unordered_map or unordered_set) will indeed only ever return 0 or 1.

Related