std映射复合键 [英] std map composite key
问题描述
我对于std :: map所需的运算符<()方法有问题。我使用一个struct作为复合键,如下所示:
I have a problem with the operator<() method which is required for a std::map. I'm using a struct as composite key that looks as follows:
struct MyKey {
std::string string1;
std::string string2;
std::string string3;
unsigned int uint1;
friend bool operator<(const MyKey& mk1, const MyKey& mk2)
{
return mk1.string1 < mk2.string1 && mk1.string2 < mk2.string2 &&
mk1.string3 < mk2.string3 && mk1.uint1 < mk2.uint1;
}
}
值,但我不知道如何实现这个为运算符< 方法。我观察到每次只存储一个值!
As introduced I want to use a composite key with 4 values, but I don't know how to achieve this for the operator< method. I observed that only 1 value is stored at a time!
任何人都可以告诉我正确的条件是什么样子?
Can anybody tell me how the right condition looks like?
提前感谢!
推荐答案
标准库的关联容器,例如 std :: map
, std :: set
, std :: multiset
std :: multimap
, std :: bitset
要求元素的排序必须遵循 严格弱订购
,这意味着您实施运算符<
必须遵循严格弱排序。所以一个实现可以是这样:
The Standard library's associative containers such as std::map
, std::set
, std::multiset
, std::multimap
, std::bitset
require that the ordering of elements must follow Strict Weak Ordering
, which means your implementation of operator<
must follow strict weak ordering. So one implementation could be this:
friend bool operator<(const MyKey& mk1, const MyKey& mk2)
{
if (mk1.string1 != mk2.string1 )
return mk1.string1 < mk2.string1;
else if ( mk1.string2 != mk2.string2)
return mk1.string2 < mk2.string2;
else if (mk1.string3 != mk2.string3)
return mk1.string3 < mk2.string3;
else
return mk1.uint1 < mk2.uint1;
}
或者您可以实现:
friend bool operator<(const MyKey& mk1, const MyKey& mk2)
{
auto const & t1 = std::tie(mk1.string1, mk1.string2, mk1.string3, mk1.uint1);
auto const & t2 = std::tie(mk2.string1, mk2.string2, mk2.string3, mk2.uint1);
return t1 < t2;
}
在此解决方案中, std :: tie
函数创建两个元组 t1
和 t1
的引用传递给它,然后比较 t1
和 t2
使用重载的运算符<
for std :: tuple
代替。用于元组的运算符<将按字典顺序比较元素,严格的弱订单。
In this solution, std::tie
function creates two tuples t1
and t1
of the references of the arguments passed to it, and then compare t1
and t2
using overloaded operator<
for std::tuple
instead. The operator< for tuple compares the elements lexicographically — strict-weak ordering is achieved..
这篇关于std映射复合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!