priority_queue<> comparison for pointers?

前端 未结 3 842
离开以前
离开以前 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条回答
  •  猫巷女王i
    2020-12-19 16:35

    You can explicitly specify which comparator your queue should use.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    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 >
    struct pless : public std::binary_function {
        bool operator()(const Type *x, const Type *y) const
            { return Compare()(*x, *y); }
    };
    
    int main(int argc, char *argv[]) {
        std::priority_queue, pless > 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;
    }
    

提交回复
热议问题