Dmitry
Dmitry

Reputation: 2158

C++ lambda for sort algorithm

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?

Upvotes: 0

Views: 387

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155418

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.

Upvotes: 4

Related Questions