How to specify a comparison for a pair?

Exist pair

pair <string, int> myPair;

I have vectorobjects myPair. I need to convert it to a mini-heap using make_heapin the second value pair, i.e. Integer. How can i do this? I am not sure how to define 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;
}
+3
source share
1 answer

Well, it make_heaphas an overload that accepts an additional comparison 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
make_heap(first,last,mypair_comp());
+8
source

All Articles