Djemon
Djemon

Reputation: 105

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:

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):

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.

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?

Upvotes: 1

Views: 349

Answers (1)

ComicSansMS
ComicSansMS

Reputation: 54679

If you just want lexicographic ordering, std::tuple will help you out:

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

Upvotes: 5

Related Questions