user8586569 user8586569 - 11 months ago 106
C++ Question

Custom comparator for achieving sort with multiple sort keys

There is an array of integers and there is a number M.
The array needs to be sorted array with respect to the following criterion:

(arr[i] % M, arr[i] / M)


That is, the ordering is determined based on the result of
arr[i] % M
, and, in case of a tie, based on the result of
arr[i] / M
.

I know that a custom comparator can be passed like this:

std::sort(arr, arr + n, comp) // comp is a custom comparator.


But the answer would probably not be correct if I apply
sort
simply twice.

Is there any way with which we can use the
std::sort()
to achieve this functionality?

Answer Source

you want the values to be sorted by arr[i]%m, and if two values are equal then you want to sort by arr[i]/m.

bool cmp(int a,int b)
{
    if(a%m < b%m)
        return true;
    if(a%m > b%m)
        return false;
    return a/m < b/m;
}

See here for a working example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download