Search code examples
c++stdmap

How to use the Compare template parameter of std::map for value comparison?


With this code:

namespace nonstd {
template <class Key,
          class T,
          class Compare = std::greater<T>,
          class Allocator = std::allocator<std::pair<Key const, T>>
          >
using map = std::map<Key, T, Compare, Allocator>;
}

int main() {
  nonstd::map<char, std::size_t> const values = {
    {'A', 3}, {'B', 2}, {'C', 5}
  };

  for (auto const& value : values) {
    std::clog << value.first << " : " << value.second << std::endl;
  }
}

I expect:

C : 5
A : 3
B : 2

But instead I got:

C : 5
B : 2 // <---
A : 3

I checked the GNU implementation of std::map and I saw the Compare template parameter we pass, will be used as a compare function for the Key:

But it also has two functions that return the comparison object:

Is there any way to use the Compare template parameter for value comparison?


Solution

  • Is there any way to use the Compare template parameter for value comparison?

    No there isnt. A std::maps elements are sorted with respect to the keys only.

    If you want a container of std::pair<char,size_t> sorted with respect to the size_ts you could use a std::set< std::pair<char,size_t>> with a custom comparator that only compares the second member. Though this will be very different from your map, because the set would only store elements with unique second (due to the custom comparator), while the map stores elements with unique keys.

    If nothing else helps you can always use a std::vector< std::pair<char,size_t>> and sort it with std::sort and use std::find_if to check for uniqueness upon insertion.