c++ - vector pair sorting by the difference of the pair elements -


is there way in c++, sort me pairs of vector based on difference of pair values. example, suppose have 4 pairs

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

so, differences of pairs 2 1 1 7, if sort in descending order sorted vector be,

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

i hope understood problem is. there way sort elements way?

i have tried way sort elements based on first or second element. not problem. problem need sort based on 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; } 

if container is

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

you sort 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 want switch between ascending , descending switch < > accordingly.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -