I have been using the C++ STL for a while but never really got around to using multisets (or multimaps). I have a question based on counting the number of elements with the same key. For eg. Here is an unordered_multiset {0, 2, 5, 1, 1, 2, 7, 5}
If I say, count(5), it should return 2. There are two ways to achieve that using the C++11 standards of unordered_multiset. 1) count 2) equal_range and then subtracting the resulting iterators.
1) is said to take linear time in number of occurrences but 2) is constant time. Why is that?
Firstly, the complexity of equal_range is documented at the link you yourself provide as:
Secondly, the logical operation of "subtracting the resulting iterators" has to be implemented using linear iteration with complexity
O(bucket_size(bucket(key)))
, stepping through a list or vector of hash-colliding values checking for the matches, so......is not a well-founded assertion.
As for "1) count", it's complexity is likewise documented- in this case:
Which again may differ from your "linear time in number of occurences". The reason that's the average is that normally with
max_load_factor
at the default of 1.0 and a good hash function, there will only be collisions as for a random scattering - something around the 10-20% mark, so most of the time the only keys hashing to a specific bucket will be those you're counting - with the average being a constant multiple around 1.1x or 1.2x that - hence linear.