Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector pair sorting by the difference of the pair elements

Tags:

c++

sorting

Is there any way in C++, That will sort me a pairs of vector based on the difference of the pair values. As an example, Suppose I have 4 pairs

1 3, 
5 6, 
2 3,
12 5,

so, the differences of the pairs are 2 1 1 7, if I sort in descending order The sorted vector would be,

12 5,
1 3,
5 6,
2 3,

I hope you understood what my problem is. Is there any way to sort the elements this way?

I have tried this way to sort elements based on first or second element. But this is not my problem. My problem is I need sort that based on the difference.

bool sortinrev(const pair<int,int> &a, const pair<int,int> &b){
    return(a.first > b.first) ;
}


int main()
{
    vector< pair <int,int> > pq;
    for(int i=1; i<=4; i++){
        int x,y;
        cin >> x >> y;

        pq.push_back(make_pair(x,y));
    }

    sort(pq.begin(), pq.end(), sortinrev);

    for(int i=0; i<4; i++){
        cout << pq[i].first << " " << pq[i].second << endl;
    }


    return 0;
}
like image 912
Yeasin Rahaman Avatar asked Dec 19 '22 05:12

Yeasin Rahaman


1 Answers

If your container is

std::vector<std::pair<int, int>> data;

you could sort it as

std::sort(std::begin(data),
          std::end(data),
          [](std::pair<int, int> const& lhs, std::pair<int, int> const& rhs)
          {
              return std::abs(lhs.first - lhs.second) < std::abs(rhs.first - rhs.second);
          });

If you want to switch between ascending and descending just switch from < to > accordingly.

like image 85
Cory Kramer Avatar answered Dec 24 '22 00:12

Cory Kramer