Search code examples
c++hashsetstdunordered-set

Why do unordered_set operations like count and erase return a size_type?


Apparently, unordered_set::erase and unordered_set::count return something that is not strictly boolean (logically, that is, I'm not talking about the actual type).

The linked page reads for the third version of erase:

size_type erase( const key_type& key );

Removes the elements with the key value key

This has a tone to it that suggests there could be more than just one element with a given key. It doesn't explicitly state this, but it sounds like it a lot.
Now, the point of a set, even an unordered one, is to have each element once.

The standard library acknowledges the existence of the bool type and uses it for boolean values like unordered_set::empty(). So, what's the point of returning size_type in the cases above? Even in spite of hash collisions, the container should distinguish elements with different keys, right? Can I still rely on that?


Solution

  • a.erase(k) size_type Erases all elements with key equivalent to k. Returns the number of elements erased.

    b.count(k) size_type Returns the number of elements with key equivalent to k.

    It's because of the unordered associative container requirements [23.2.5].