所以我正在使用带有指针的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));
Run Code Online (Sandbox Code Playgroud)
现在我如何编写一个比较函数来获得在Q中正确排序的函数?或者,有人可以提出替代策略吗?我真的需要priority_queue接口,并且不想使用复制构造函数(因为有大量数据).谢谢
编辑: Int只是一个占位符/示例......我知道我可以int
在C/C++中使用大声笑...
eph*_*ent 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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6422 次 |
最近记录: |