带有节点指针的STL堆

时间:2011-12-28 17:23:24

标签: c++ stl

我有一个带有成员的Node类

int weight;
Node *left;
Node *right;

我想使用STL函数

创建堆
make_heap(Iterator , Iterator, comp) 
pop_heap(Iterator, Iterator, comp)

应用于Node指针的向量。如何为这些函数创建比较对象(或比较函数)?

2 个答案:

答案 0 :(得分:2)

struct node_comparison : public std::binary_function< const Node*, const Node*, bool > 
{
    bool operator()( const Node* const a, const Node* const b ) const 
    {
        return a->weight < b->weight;
    }
};

请注意,此比较对象仅比较 权重,但我认为这是期望的行为。

答案 1 :(得分:1)

如果您通过operator<为对象提供严格的弱排序,则可以调用make_heappop_heap等的重载,这些重载甚至不需要第三个参数。 comp是您可以选择自定义比较的。

class Node
{
int weight;
Node *left;
Node *right;

public:
bool operator<(const Node& rhs) const { return weight < rhs.weight; }
};