优先级队列>>比较指针?
所以我使用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
哈哈...
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));
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 is just a placeholder/example... I know I can just use int
in C/C++ lol...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以明确指定队列应使用哪个比较器。
You can explicitly specify which comparator your queue should use.
一种肯定有效的选择是将
Int*
替换为shared_ptr
,然后为shared_ptr实现
operator<
。One option that will surely work is to replace
Int*
withshared_ptr<Int>
and then implementoperator<
forshared_ptr<Int>
在 32 位系统上,整数的大小与指针的大小相同。在 64 位系统上,指针将是原来的两倍。因此,使用常规整数更简单/更快/更好。
An integer is the same size as a pointer on 32 bit systems. On 64 bit systems, a pointer will be twice as big. Therefore, it is simpler/faster/better to use regular integers.