user8586569 user8586569 - 3 years ago 230
C++ Question

How to create a custom sort function for c++ stl

There is an array of integers and there is a number M,the output required is a sorted array with the following property:

(arr[i]%M,arr[i]/M),i.e first a sort on the arr[i]%M is required , then apply another sort on similar arr[i]%M values by their arr[i]/M values.

I know that a custom sort function can be created like this:

sort(arr,arr+n,comp)//comp is a customized object.

But, the answer would not be correct if I apply sort like this,i.e. 2 separate times.

Is there any way with which we can use the stl sort function to achieve this funcionality?


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