简体   繁体   English

使用联合作为 std::unordered_map 的键

[英]Using union as key for std::unordered_map

I want to use union with a structure{int, int, string} and integer as a key for unordered_map.我想将 union 与结构 {int, int, string} 和 integer 用作 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.我想坚持 C++11 所以不能使用变体。

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.哈希器需要知道哪个联合成员处于活动状态,然后应用适合该类型的 hash function 。 Since it is not possible to find out the active member by inspecting the union object, this quite tricky.由于无法通过检查工会 object 来找出活动成员,这非常棘手。

Instead of union, in practice you need to use some sort of "tagged union" type such as std::variant .而不是联合,实际上您需要使用某种“标记联合”类型,例如std::variant Despite the name, tagged union is typically implemented without using union internally in C++.尽管名称如此,标记联合通常在 C++ 内部不使用联合来实现。 If you cannot use C++17, then you need to use some other implementation or write one yourself.如果你不能使用 C++17,那么你需要使用一些其他的实现或者自己写一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM