How to sort an array in c++ by the second column in reverse order?

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil” , remember that and start using vectors again , :stuck_out_tongue:

  1. http://ayurjain.blogspot.in/ His tutorials are good…
  2. http://e-maxx.ru/algo/
  3. http://codeforces.com/blog/entry/619
1 Like

Can anyone explain it in a simple way?

The compare function, compares the second element of pair and returns true to sort function if p1.second>p2.second otherwise false, based on these boolean values, sort function judges the position of the pair in array. If you are not clear with Sorting function read regd merge sort : https://en.wikipedia.org/wiki/Merge_sort

Thank you!

C++ also supports lambda functions. Assuming you store the array as a vector of pairs:

sort(v.begin(), v.end(), [&](const pair<int, int>& a, const pair<int, int>& b) {
    return a.second > b.second;
});
1 Like