鉴于std::vector
个Custom
个对象,我想根据多个查询(我首先在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
等于我想要做的排序查询的数量。
是否有一些高级逻辑技巧可能仍然可以实现这一点,或者在单个比较运算符中对多个属性进行排序,这是不可能的?
答案 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);
}