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?

1
  • If you're not using namespace std; (you shouldn't be), you're missing an awful lot of std:: namespace prefixes. Also, you should declare your parameters const; you're not mutating them after all. Commented Oct 27, 2020 at 15:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.