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

时间:2016-10-15 12:21:38

标签: c++ algorithm sorting c++11

鉴于std::vectorCustom个对象,我想根据多个查询(我首先在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等于我想要做的排序查询的数量。

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

1 个答案:

答案 0 :(得分:4)

如果您只想要词典排序,std::tuple会帮助您:

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