繁体   English   中英

如何基于第一或第二个较大的值对对数组进行排序

[英]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;
}

我的目标是基于更大的值对对数组进行排序。
我不在乎更大的值是该对中的第一个或第二个元素。

例如我有这对:

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

这个给你

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(pair<int, int> i, pair<int, int> j) { return max(i.first, 
i.second) > max(j.first, j.second); }

尚未测试,也未尝试进行编译,但希望您可以从这里解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM