0

I'd like to sort a map<pair<string, int>, int> dbg; by value using lambda :

For this I have

void test()
{
   map<pair<string, int>, int> dbg;
   sort( dbg.begin(), dbg.end(),
         []( pair<pair<string, int>, int>& lht, pair<pair<string, int>, int>& rht) {
      return lht.second > rht.second;
   });
}

But compilation failed with a lot of errors. What is the right lamda prototype here?

Zig Razor
  • 3,381
  • 2
  • 15
  • 35
Dmitry
  • 1,912
  • 2
  • 18
  • 29
  • If you're not `using namespace std;` ([you shouldn't be](https://stackoverflow.com/q/1452721/364696)), you're missing an awful lot of `std::` namespace prefixes. Also, you should declare your parameters `const`; you're not mutating them after all. – ShadowRanger Oct 27 '20 at 15:28

1 Answers1

4

Sorting a map is nonsensical; it's already sorted, and you can't change the sort order after the fact by sorting it (the order can't be changed at all except by adding and removing elements, and they'll always fall into a fixed order). If you want to sort it in a different way, either:

  1. Provide the alternate comparator to map so it's naturally sorted the way you want, or
  2. Copy the entries to sequence type (e.g. vector) and sort that.

In this case, you want to sort by the value, which is not possible for a map, so option #2 is your only option.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271