6

有一个pair

pair <string, int> myPair;

我有一个vector对象myPair。我需要使用整数make_heap的第二个值将它转换为最小堆。pair我怎样才能做到这一点?我不确定如何定义比较操作。

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;
}
4

1 回答 1

10

好吧,make_heap有一个需要额外比较运算符的重载,所以...

// 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());
于 2011-05-15T22:21:58.470 回答