[英]std::sort - given a custom sort function, are multiple sort queries in one comparison possible?
给定一个Custom
对象的std::vector
,我想根据多个查询对这个列表进行排序(我首先在value1
上排序,然后在value2
上排序),所以:
bool customSort(const Custom &a, const Custom &b)
{
return value1 < b.value1 && a.value2 < b.value2;
}
std::vector<Custom> elements;
std::sort(elements.begin(), elements.end(), customSort);
不幸的是,这不起作用(因为它会发生customSort(a,b)
和customSort(b,a)
等于true
),因此我必须这样排序(以相反的顺序):
bool customSortValue1(const Custom &a, const Custom &b)
{
return value1 < b.value1;
}
bool customSortValue2(const Custom &a, const Custom &b)
{
return value2 < b.value2;
}
std::vector<Custom> elements;
// note that I first sort by customSortValue2 and than customSortValue1
std::sort(elements.begin(), elements.end(), customSortValue2);
std::sort(elements.begin(), elements.end(), customSortValue1);
哪个有效,但显然效率较低,因为我必须遍历整个向量n
次,其中n
等于我想要执行的排序查询的数量。
是否有一些高级逻辑技巧可能仍然使这成为可能,或者在单个比较运算符中对多个属性进行排序本质上是不可能的?
如果您只想按字典顺序排序, std::tuple
将帮助您:
bool customSort(const Custom &a, const Custom &b)
{
return std::tie(a.value1, a.value2) < std::tie(b.value1, b.value2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.