[英]Using A Struct As Key For std::unordered_map
I am trying to use a struct as a key for an unordered_map
.我正在尝试使用 struct 作为unordered_map
的键。 I added the 'spaceship' operator to the structure, which solved errors I was getting with normal comparisons, such as "is struct 1 greater than struct 2?", etc. However, I am getting attempting to reference a deleted function
when using it as a key for my map.我在结构中添加了“宇宙飞船”运算符,这解决了我在正常比较时遇到的错误,例如“结构 1 是否大于结构 2?”等。但是,我在使用它时attempting to reference a deleted function
作为我地图的钥匙。 From what understood, adding the spaceship operator should have allowed me to use the struct as the map key.据了解,添加 spaceship 运算符应该允许我使用 struct 作为映射键。 What is wrong?怎么了?
struct test
{
uint32_t a;
uint32_t b;
auto operator<=>(const test&) const = default;
};
std::unordered_map<test, uint32_t> x; // Causes error
To use a structure as a key in an unordered_map, you need two things:要将结构用作 unordered_map 中的键,您需要做两件事:
A "hasher", something that will take a const test &
and compute a hash, which defaults to std:hash<test>
, and一个“哈希器”,它将接受一个const test &
并计算一个哈希值,默认为std:hash<test>
,以及
A comparison predicate, which defaults to std::equal_to<test>
.比较谓词,默认为std::equal_to<test>
。
You've got the second one covered with your spaceship operator, but not the first.你的宇宙飞船操作员已经覆盖了第二个,但不是第一个。 There is no std::hash<test>
.没有std::hash<test>
。
See C++ unordered_map using a custom class type as the key for an example as how to define your own hasher.有关如何定义自己的哈希器的示例,请参阅使用自定义类类型作为键的 C++ unordered_map 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.