Search code examples
c++sortingcomparatormultimap

How to sort std::multimap entries based on keys and values via custom Compare predicate?


I'm looking for a way to sort std::multimap's entries in ascending order by keys, but if the keys match, in descending order by values.

Is it possible to implement with a custom Compare predicate?


Solution

  • Map's Compare predicate only takes keys as arguments. Unfortunately you cannot use values to sort the entries within the same bucket with use of the predicate only.

    Important - it's still possible to implement such scenario it with other means. Here is the answer how to do it if you are ok to use emplace_hint.


    The keys are sorted in ascending order by default with use of std::less. In order to implement a custom predicate, you can use a lambda (or any other form of the binary predicate):

    const auto lessPredicate = [](const MyClass& lhs, const MyClass& rhs) {
        return lhs.value < rhs.value;
    };
    std::multimap<MyClass, std::string, decltype(lessPredicate)> my_map { lessPredicate };