STD ::用自定义密钥的地图
我想使用具有以下自定义密钥的标准地图:
struct ParserKey{
ParserKey(uint16_t compno,
uint8_t resno,
uint64_t precinctIndex) : compno_(compno),
resno_(resno),
precinctIndex_(precinctIndex)
{
}
uint16_t compno_;
uint8_t resno_;
uint64_t precinctIndex_;
};
不过,没有明显的订购钥匙的方法。 可以订购这些钥匙,还是我需要不同的关联集合?
I would like to use a standard map with the following custom key:
struct ParserKey{
ParserKey(uint16_t compno,
uint8_t resno,
uint64_t precinctIndex) : compno_(compno),
resno_(resno),
precinctIndex_(precinctIndex)
{
}
uint16_t compno_;
uint8_t resno_;
uint64_t precinctIndex_;
};
There's no obvious way of ordering the keys, though.
Can these keys be ordered, or do I need a different associative collection ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不在乎特定的顺序,而只想满足排序的要求,那么一种常见而简单的模式是使用
std :: tie
与比较实例的所有类成员一起,然后比较这些结果。std :: tie
创建std :: tuple
引用到成员的参考,并且std :: Tuple
实现操作员< 在词典上比较其元素(在这种情况下对象的成员)。
在您的情况下,使用成员
操作员<
:live示例 https: / /v433v54jz
If you don't care about the specific order and just want to satisfy the requirements for sorting, a common and simple pattern is to use
std::tie
with all of the class members of the compared instances, and compare those results instead.std::tie
creates astd::tuple
of references to the members, andstd::tuple
implementsoperator<
which compares its elements (the members of the object in this case) lexicographically.In your case, using member
operator<
:Live example https://godbolt.org/z/v433v54jz
您只需以与
std
std std ::词典_compare
做到了。
因此,懒惰的方法是:
但是它带有将您的成员压入峰值容器的开销。如果您不想要那个,则可能必须重新实现词典图比较自己。
You can just impose any arbitrary total order on these integers in the same style as
std::lexicographical_compare
does.So, the lazy approach is:
But it carries the overhead of pressing your members into an iterable container. If you don't want that, you might have to reimplement a lexicographical compare yourself.
在C ++ 20中,您可以做到这一点:(在类范围内)
不要忘记
#include&lt;比较
。这将为您提供所有6个关系操作员:
==
,!=
,&lt;
,&lt; =
,&gt;
,&gt; =
,执行词典比较(与 @françoisandRieux的答案相同)。In C++20 you can do this: (at class scope)
Don't forget to
#include <compare>
.This will give you all 6 relational operators:
==
,!=
,<
,<=
,>
,>=
, performing lexicographical comparison (same as in @FrançoisAndrieux's answer).