c++arrayssortingvectorcustom-function

How do I sort array of pairs based on the greater value in first or second


bool custome_compare(const pair<int, int>& p1, const pair<int, int>& p2){
    if (p1.first > p1.second || p1.second > p1.first) return true;
    else return false;
}
int main()
{
    pair<int, int> arr[4];
    arr[0].first = 4, arr[0].second = 10;
    arr[1].first = 7, arr[1].second = 6;
    arr[2].first = 3, arr[2].second = 8;
    arr[3].first = 9, arr[3].second = 1;

    sort(arr, arr + 4 , custome_compare);
    //---------------------------------------
    return 0;
}

My goal to sort the array of pairs based on the greater value.
I don't care the greater value is the first or the second element in the pair.

For example i have this pairs:

4,10
7,6
3,8
9,1

After sort them :

4,10
9,1
3,8
7,6

So i'm not sorting based on first or second i sorting based on both.

How can I edit this compare function to do this task ?

Thanks in advance.


Solution

  • It sounds like you want to compare the max of the two pairs.

    bool custom_compare(const pair<int, int>& p1, const pair<int, int>& p2){
        return std::max(p1.first, p1.second) < std::max(p2.first, p2.second); 
        }