Home > Software engineering >  fields use to implement hash and comparison functions in unordered_map
fields use to implement hash and comparison functions in unordered_map

Time:09-29

Is it necessary for the comparison and the hash function of a custom type in an std::unordered_map to use the same set of fields? (i.e) given:

struct Foo { int i; float f; };

If I generate hashes only using i but use both i and f to implement equality, will I run afoul of anything? In my understanding, the comparison function is used to determine the relative ordering of objects within a bucket. So I don't think there should be a problem but I am not 100% sure.

CodePudding user response:

That's fine, all that is required is that x == y implies hash(x) == hash(y) which your scheme does.

  • Related