所以我用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++ lol中使用int .
发布于 2009-10-05 01:26:33
一个肯定有效的选择是用Int*替换shared_ptr<Int>,然后为shared_ptr<Int>实现operator<。
bool operator<(const shared_ptr<Int> a, const shared_ptr<Int> b)
{
return a->getVal() < b->getVal();
}发布于 2009-10-05 03:22:37
您可以显式指定您的队列应该使用哪个比较器。
#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;
}发布于 2009-10-05 01:10:12
整数与32位系统上的指针大小相同。在64位系统中,指针的大小是原来的两倍。因此,使用正则整数更简单/更快/更好。
https://stackoverflow.com/questions/1517854
复制相似问题