priority_queue<>比较指针?

时间:2009-10-05 01:06:40

标签: c++ templates stl

所以我正在使用STL priority_queue<>使用指针...我不想使用值类型,因为创建一堆新对象只是为了在优先级队列中使用会非常浪费。所以......我正在努力做到这一点:

class Int {
public:
    Int(int val) : m_val(val) {}
    int getVal() { return m_val; }
private:
    int m_val;
}


priority_queue<Int*> myQ;

myQ.push(new Int(5));
myQ.push(new Int(6));
myQ.push(new Int(3));

现在如何编写比较函数以在Q中正确排序?或者,有人可以提出替代策略吗?我真的需要priority_queue接口,并且不想使用复制构造函数(因为有大量数据)。感谢

编辑: Int只是一个占位符/示例...我知道我可以在C / C ++中使用int大声笑......

3 个答案:

答案 0 :(得分:10)

您可以明确指定队列应使用哪个比较器。

#include <iostream>
#include <sstream>
#include <functional>
#include <vector>
#include <queue>

class Int {
public:
    Int(int val) : m_val(val) {}
    int getVal() { return m_val; }
    bool operator<(const Int &other) const { return m_val < other.m_val; }
private:
    int m_val;
};

template<typename Type, typename Compare = std::less<Type> >
struct pless : public std::binary_function<Type *, Type *, bool> {
    bool operator()(const Type *x, const Type *y) const
        { return Compare()(*x, *y); }
};

int main(int argc, char *argv[]) {
    std::priority_queue<Int*, std::vector<Int*>, pless<Int> > myQ;

    for (int i = 1; i < argc; i++) {
        std::stringstream ss(argv[i]);
        int x;
        ss >> x;
        myQ.push(new Int(x));
    }

    for (; !myQ.empty(); delete myQ.top(), myQ.pop())
        std::cout << myQ.top()->getVal() << std::endl;

    return 0;
}

答案 1 :(得分:3)

一定可行的选项是将Int*替换为shared_ptr<Int>,然后为operator<实施shared_ptr<Int>

bool operator<(const shared_ptr<Int> a, const shared_ptr<Int> b)
{
    return a->getVal() < b->getVal();
}

答案 2 :(得分:0)

整数与32位系统上的指针大小相同。在64位系统上,指针将是两倍大。因此,使用常规整数更简单/更快/更好。