priority_queue<> comparison for pointers?

前端 未结 3 841
离开以前
离开以前 2020-12-19 15:32

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

相关标签:
3条回答
  • 2020-12-19 16:27

    One option that will surely work is to replace Int* with shared_ptr<Int> and then implement operator< for shared_ptr<Int>

    bool operator<(const shared_ptr<Int> a, const shared_ptr<Int> b)
    {
        return a->getVal() < b->getVal();
    }
    
    0 讨论(0)
  • 2020-12-19 16:32

    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.

    0 讨论(0)
  • 2020-12-19 16:35

    You can explicitly specify which comparator your queue should use.

    #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;
    }
    
    0 讨论(0)
提交回复
热议问题