【问题标题】:priority_queue<> comparison for pointers?priority_queue<> 比较指针?
【发布时间】:2009-10-05 01:06:40
【问题描述】:

所以我将 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 大声笑...

【问题讨论】:

    标签: c++ templates stl


    【解决方案1】:

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

    #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;
    }
    

    【讨论】:

      【解决方案2】:

      一个肯定可行的选择是将Int*替换为shared_ptr&lt;Int&gt;,然后为shared_ptr&lt;Int&gt;实现operator&lt;

      bool operator<(const shared_ptr<Int> a, const shared_ptr<Int> b)
      {
          return a->getVal() < b->getVal();
      }
      

      【讨论】:

      • 我现在正在尝试这种方法...而不是使用 shared_ptr 只是使用一个基本的包装类。
      • @Polaris878 虽然共享指针在这里无关紧要。你从来没有说过你想要共享所有权。
      【解决方案3】:

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

      【讨论】:

      • Int 只是一个更大类的占位符。
      • 在这种情况下,忽略此响应。
      猜你喜欢
      • 2018-12-17
      • 2017-01-19
      • 2012-07-01
      • 2016-05-13
      • 2012-02-23
      • 2012-10-05
      • 2018-10-18
      相关资源
      最近更新 更多