How to make a map sort by value C++

后端 未结 5 1220
情话喂你
情话喂你 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:18

    The first, simple problem is

    struct compareByVal {
      bool operator[](const std::pair & a, const std::pair & b)
        return a.second < b.second;
    }
    

    should be

    struct compareByVal {
      bool operator()(const std::pair & a, const std::pair & b) const {
        return a.second < b.second;
      }
    };
    

    The second, serious problem is the signature of the compare is wrong. It should be

    struct compareByVal {
      bool operator()(const int leftKey, const int rightKey) const;
    }
    

    You can't access the value in the compare function. There is no (simple) way to sort a map by value.

提交回复
热议问题