Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 952
bitmask Avatar asked Aug 08 '12 07:08

bitmask


2 Answers

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].

like image 74
ForEveR Avatar answered Nov 15 '22 03:11

ForEveR


It's probably just so that they could re-use the wording from unordered_multiset. You don't have to worry about hash collisions except for performance-wise, the container is still correct even if every element collides- even if such a thing would be stupendously slow.

like image 28
Puppy Avatar answered Nov 15 '22 04:11

Puppy