0

I want to use union with a structure{int, int, string} and integer as a key for unordered_map. What are the best practices to do this? How does the hashing work, is there need for custom hashing?

struct nodeinfo {
int a;
int b;
string c;
};

union key{
nodeinfo structKey;
int intKey; 
};

unordered_map<key, int> Map;

I want to stick to C++11 so cannot use variant.

blarredflunky
  • 43
  • 1
  • 4
  • I'm not sure how you intend to implement equality comparison or hashing for your `key` type, given that there is no information on which member is active. Possible duplicate of [What is the correct way to check equality between instances of a union?](https://stackoverflow.com/questions/12195794/what-is-the-correct-way-to-check-equality-between-instances-of-a-union). – François Andrieux Nov 13 '19 at 19:13
  • There are several implementations for `std::variant` that work with C++11, such as this one: https://github.com/mpark/variant . – parktomatomi Nov 13 '19 at 19:14

1 Answers1

3

What are the best practices to do this?

Best practice is probably to not do this.

is there need for custom hashing?

Yes.

How does the hashing work

The hasher somehow needs to know which union member is active, and then apply a hash function appropriate for that type. Since it is not possible to find out the active member by inspecting the union object, this quite tricky.

Instead of union, in practice you need to use some sort of "tagged union" type such as std::variant. Despite the name, tagged union is typically implemented without using union internally in C++. If you cannot use C++17, then you need to use some other implementation or write one yourself.

eerorika
  • 232,697
  • 12
  • 197
  • 326