我如何根据第一或第二个对更大的值对成对排序

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

本文关键字:排序 第二个 何根      更新时间:2023-10-16
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;
}

我的目标是根据更大的值对成对阵列进行排序。
我不在乎更大的价值是这对的第一个或第二个元素。

例如,我有这对:

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

对它们进行排序:

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

所以我不是基于第一个或第二个基于两个基于两者进行排序的排序。

如何编辑此比较函数以完成此任务?

预先感谢。

您是

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

这是一个指示的程序

#include <iostream>
#include <utility>
#include <algorithm>
#include <iterator>
bool custome_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2)
{
    return std::max( p1.first, p1.second ) > std::max( p2.first, p2.second );
}
int main() 
{
    std::pair<int, int> arr[] = 
    {
        { 4, 10 }, { 7, 6 }, { 3, 8 }, { 9, 1 }
    };

    for ( const auto &p : arr )
    {
        std::cout << p.first << ", " << p.second << 'n';
    }
    std::cout << std::endl;
    std::sort( std::begin( arr ), std::end( arr ), custome_compare );
    for ( const auto &p : arr )
    {
        std::cout << p.first << ", " << p.second << 'n';
    }
    std::cout << std::endl;
    return 0;
}

其输出是

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

听起来您想比较两对的最大值。

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); 
    }

自定义比较函数应比较对(s)的最大值。所以类似:

bool custom_compare(pair<int, int> i, pair<int, int> j) { return max(i.first, 
i.second) > max(j.first, j.second); }

未经测试,也没有尝试编译,但我希望您可以从这里解决问题。

相关文章: