2017-12-07 22 views
0
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; 
} 

大きな値に基づいてペアの配列を並べ替えるという私の目標です。
大きな値は、ペアの最初または2番目の要素です。ソートそれらの後第1または第2の大きな値に基づいてペアの配列をソートするには

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

:たとえば

私はこのペアを持っている

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

だから私は両方に基づいて、第1または第二私は、ソートに基づいて並べ替えていませんよ。

どのように私はこの作業を行うには、この比較関数を編集することができますか?

ありがとうございます。

答えて

1

2つのペアの最大値を比較したいと思うようです。ここで

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

あなたはここで

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 
1

カスタムの最大値を比較する必要コンペア機能でありますペア。そうですね、

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

コンパイルは試していませんが、ここから作業してください。

+0

私の答えを入力している間、コロポップは答えました:-) そして、より良いバージョンでは、constと参照を使用します。 – Slay

関連する問題