简体   繁体   English

std::sort - 给定一个自定义排序函数,是否可以在一次比较中进行多个排序查询?

[英]std::sort - given a custom sort function, are multiple sort queries in one comparison possible?

Given a std::vector of Custom objects, I want to sort this list according to multiple queries (where I first sort on value1 and then on value2 ) so:给定一个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);

Unfortunately, this doesn't work (as it will happen that customSort(a,b) and customSort(b,a) equal true ) and I thus have to sort like this (in reverse order):不幸的是,这不起作用(因为它会发生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);

Which works, but is obviously less efficient as I have to traverse the entire vector n times with n being equal to the number of sorting queries I want to do.哪个有效,但显然效率较低,因为我必须遍历整个向量n次,其中n等于我想要执行的排序查询的数量。

Is there some advanced logic trick that might still make this possible or is sorting on multiple properties within a single comparison operator inherintly impossible?是否有一些高级逻辑技巧可能仍然使这成为可能,或者在单个比较运算符中对多个属性进行排序本质上是不可能的?

If you just want lexicographic ordering, std::tuple will help you out:如果您只想按字典顺序排序, 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.

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