mercredi 28 mars 2018

C++ custom comparator not working MWE

I know there has been few posts about this already, so feel free to remove my post, but this code:

#include <bits/stdc++.h>
#define tol 1e-9
using namespace std;

int n;
vector<pair<double,double>> vec;

struct comparator {
    bool operator () ( pair<double,double> &a, pair<double,double> &b ) {
        if ( fabs(a.first-b.first) < tol )
            return a.second < b.second;
        return a.first > b.first;
    }
};

int main() {
    int i,j,k,ts,cs= 0,m,sz;
    for ( ; 1 == scanf("%d",&n); ) {
        for ( vec.clear(), vec.reserve(n), i = 0; i < n; ++i )
            scanf("%lf %lf",&vec[i].second,&vec[i].first);
        sort(vec.begin(),vec.end(),comparator());
        for ( i = 0; i < n; ++i )
            printf("%lf %lf\n",vec[i].first,vec[i].second);
    }
    return 0;
}

is not working for this example:

2
120 60
60 90

I compile this as g++ -std=c++11 -o a mwe.cpp, and mine is g++ version 5.4

Aucun commentaire:

Enregistrer un commentaire