deevee deevee - 3 years ago 111
C++ Question

How to specifiy comparison for pair?

There is a


pair <string, int> myPair;

I have a
objects. I need to convert it to a min-heap using
on the second value of
i.e. the integer. How can I do that? I am not sure on how to define the comparison operations.

I know I need something like this for heap to operate. But not sure where to put it:

bool operator< (const Pair& p1, const Pair& p2) const
return p1.second < p2.second;

Xeo Xeo
Answer Source

Well, make_heap has an overload that takes an extra comparision operator, soo...

// somewhere in global namespace
typedef std::pair<std::string, int> myPair_type;

struct mypair_comp{
  bool operator()(myPair_type const& lhs, myPair_type const& rhs){
    return lhs.second < rhs.second;

// somewhere at your callside
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download