-3

以下は私のコードです。operat機能が正常に動作していません。どんな助けでもありがたいです。通常、sort昇順で並べ替えます。降順でソートされるようにoperatを定義したい

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<utility>
using namespace std;
typedef pair<int,int> pii;
typedef pair<int,pii> pwp;

bool operat(pwp a, pwp b){
    if(a.first > b.first){
        return true;
    }else if(a.second.first > b.second.first) {
        return true;

    }else if (a.second.second > b.second.second) { return true;}
    return false;

}
int main(){
    vector<pwp> inp;
    pwp obj1 = make_pair(1998,make_pair(3,24));
    pwp obj2 = make_pair(1998,make_pair(3,21));
    pwp obj3 = make_pair(1997,make_pair(3,24));
    inp.push_back(obj1);
    inp.push_back(obj2);
    inp.push_back(obj3);
    printf("Before sorting\n");
    for(int i = 0 ; i< inp.size();i++){
        pwp sth = inp[i];
        printf("%d %d %d\n",sth.first,sth.second.first,sth.second.second);

    }
    sort(inp.begin(), inp.end(),operat);
    cout<<"After soring"<<endl;
    for(int i = 0 ; i< inp.size();i++){
        pwp sth = inp[i];
        printf("%d %d %d\n",sth.first,sth.second.first,sth.second.second);
    }
return 0;
}

新しいもの:

bool operat(pwp a, pwp b){
    if(a.first > b.first){
        return true;
    }else if(a.first <  b.first) return false;

    else if(a.second.first > b.second.first) {
        return true;

    }else if (a.second.first < b.second.first) return false;
    else if (a.second.second > b.second.second) { return true;}
    return false;

}
4

2 に答える 2

4

std :: pairには比較演算子が付属しており、テンプレート引数にこれらの演算子がある場合に機能します。したがって、 std::greaterインスタンスを比較ファンクターとして使用できます。

#include <functional> // for std::greater

operat = std::greater<pwp>();
std::sort(inp.begin(), inp.end(),operat);

std::greater何らかの理由で使用するのが難しすぎる場合は、次のように関数operatを定義することもできます。

bool operat(const pwp& a, const pwp& b){ return a > b; }

字句比較ロジックを自分で実装することを主張する場合は、次のことをお勧めします。正しく比較する方法を理解しようとするのではなく、一般的std::pair<int, std::pair<int, int>>に比較する方法を理解します。std::pair<T1,T2>次に、そのロジックをの比較に使用しstd::pair<T1, std::pair<T2, t3>>ます。

于 2013-01-30T07:36:52.463 に答える
2

あなたのコードでは:

bool operat(pwp a, pwp b){
    if(a.first > b.first){
        return true;
    }else if(a.second.first > b.second.first) {
        return true;
    }else if (a.second.second > b.second.second) { return true;}
    return false;
}

2番目の比較は、a.first == b.firstの場合にのみ実行し、3番目の比較はa.second.first==b.second.firstの場合にのみ実行する必要があります。

于 2013-01-30T07:36:10.450 に答える