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

Dje*_*mon 1 c++ sorting algorithm c++11

给定一个std::vector对象Custom,我想根据多个查询对该列表进行排序(我首先对 on 进行排序value1,然后对 on 进行排序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);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用(因为它会发生customSort(a,b)并且customSort(b,a)equal 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);
Run Code Online (Sandbox Code Playgroud)

这是有效的,但显然效率较低,因为我必须遍历整个向量n时间,并且n等于我想要执行的排序查询的数量。

是否有一些高级逻辑技巧仍然可以实现这一点,或者在单个比较运算符中对多个属性进行排序本质上是不可能的?

Com*_*sMS 5

如果您只想按字典顺序排序,std::tuple将帮助您:

bool customSort(const Custom &a, const Custom &b)
{
    return std::tie(a.value1, a.value2) < std::tie(b.value1, b.value2);
}
Run Code Online (Sandbox Code Playgroud)