Let's take unordered_set for example.
The default predicate for determining if two elements are equal is std::equal_to<T>(t1,t2)
,
which is simply t1==t2
.
Now lets suppose that for this T type I've implemented operator==()
so that not all member variables are part of this comparison, i.e two different T elements t1,t2 can be equal on comparison.
If the underlying hashtable calculates a different hash for each of these t1 and t2, when does it even perform the t1==t2
check for duplication of keys? and if there are more checks, how does it stay constant-time on average?
I think the key point that you're missing is that you supply two functors to the unordered container, and they have to work together.
There's the hash function, which calculates a number from an object.
There's a comparison function, which compares two objects for "equivalence".
As @Eljay said in his comment, for two objects that compare "equivalent" (the comparison function returns true
), the hash function must return the same value.
If your functions do not provide this guarantee, then the containers will not work correctly.
std::unordered_set: Meets the requirements of UnorderedAssociativeContainer.
UnorderedAssociativeContainer: are parameterized by Key/Hash/Pred.
With the requriement:
* If two Keys are equal according to Pred.
* Hash must return the same value for both keys.