How to specifiy comparison for pair?
14,489
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
make_heap(first,last,mypair_comp());
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 25, 2022Comments
-
Admin about 2 years
There is a
pair
pair <string, int> myPair;
I have a
vector
ofmyPair
objects. I need to convert it to a min-heap usingmake_heap
on the second value ofpair
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; }
-
John Zwinck about 13 yearsPretty much this, though the lhs & rhs arguments need to be of some type, so either myPair should be a typedef (rather than a variable), or some typedef should be created.
-
Xeo about 13 years@John Zwinck: Woops, totally saw that as a typedef, lol.. Edited. :)