首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >指针的priority_queue<>比较?

指针的priority_queue<>比较?
EN

Stack Overflow用户
提问于 2009-10-05 01:06:40
回答 3查看 7.1K关注 0票数 4

所以我用STL priority_queue<>和指针..。我不想使用值类型,因为仅仅为了在优先级队列中使用而创建一堆新对象是非常浪费的。所以..。我想这么做:

代码语言:javascript
复制
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 .

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-10-05 01:26:33

一个肯定有效的选择是用Int*替换shared_ptr<Int>,然后为shared_ptr<Int>实现operator<

代码语言:javascript
复制
bool operator<(const shared_ptr<Int> a, const shared_ptr<Int> b)
{
    return a->getVal() < b->getVal();
}
票数 3
EN

Stack Overflow用户

发布于 2009-10-05 03:22:37

您可以显式指定您的队列应该使用哪个比较器。

代码语言:javascript
复制
#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;
}
票数 10
EN

Stack Overflow用户

发布于 2009-10-05 01:10:12

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1517854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档