priority_queue<>指针比较? [英] priority_queue<> comparison for pointers?
问题描述
所以我使用带有指针的STL priority_queue<> ...我不想使用值类型,因为创建一大堆新对象只是用于优先级队列将是非常浪费。所以...我想这样做:
So I'm using the STL priority_queue<> with pointers... I don't want to use value types because it will be incredibly wasteful to create a bunch of new objects just for use in the priority queue. So... I'm trying to do this:
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接口,并希望不使用复制构造函数(因为大量的数据)。感谢
Now how can I write a comparison function to get those to be ordered correctly in the Q? Or, can someone suggest an alternate strategy? I really need the priority_queue interface and would like to not use copy constructors (because of massive amounts of data). Thanks
EDIT: Int只是一个占位符/示例...我知道我可以使用 int
在C / C ++ lol ...
Int is just a placeholder/example... I know I can just use int
in C/C++ lol...
推荐答案
一个选择肯定会工作是替换
with
shared_ptr< Int>
,然后实现 operator<
code> shared_ptr< Int>
One option that will surely work is to replace Int*
with shared_ptr<Int>
and then implement operator<
for shared_ptr<Int>
bool operator<(const shared_ptr<Int> a, const shared_ptr<Int> b)
{
return a->getVal() < b->getVal();
}
这篇关于priority_queue<>指针比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!