How to make a map sort by value C++

后端 未结 5 1228
情话喂你
情话喂你 2021-01-29 08:08

I was trying to make a map sort by value using a custom comparator but I couldn\'t figure out why I kept getting the error of \"no matching call to compareByVal\"

Here\'

5条回答
  •  爱一瞬间的悲伤
    2021-01-29 08:29

    Well, first, the reason you're getting the error: "no matching call to compareByVal" is because map's comparator works only with the keys. So the comparator should like:

    struct compareByVal {
      template 
      bool operator()(const T& a, const T& b) const
        return a < b;
    }
    

    Coming on to what you want to achieve, I see two ways of doing so:

    1. Copy all the elements of the map to a std::vector and sort that:
    std::vector > v(hash.begin(), hash.end());
    std::sort(v.begin(), v.end(), [](const auto& a, const auto& b) { return a.second < b.second; });
    
    1. Copy all the elements of the map to another map with keys as values and values as keys. If values of your map are not unique, you can use a std::multimap instead.

提交回复
热议问题