c++ - 如何根据第一个或第二个中的较大值对数组对进行排序

标签 c++ arrays sorting vector custom-function

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

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

如何编辑这个比较函数来完成这个任务?

提前致谢。

最佳答案

给你

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

关于c++ - 如何根据第一个或第二个中的较大值对数组对进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47701888/

相关文章:

javascript - 在 JavaScript 中解析数组的数组

R如何有选择地对数据框进行排序?

Java 6 排序数组

c++ - 未知类型名称类

c++ - std::map::iterator 递减单个元素

c++ - 模板函数参数的含义是什么?

javascript - 将循环数组分配给对象

javascript - 数据属性列表到数组

sql按子组总和数据排序

c++ - 将 C 识别的指针类型定义为内部 C++ 类