How to move elements out of STL priority queue

后端 未结 2 948
别跟我提以往
别跟我提以往 2021-01-11 19:14

C++\'s STL priority queue have a void pop() method, and a const ref top() method. Thus, if you want to move elements out of the queue, you have to do something like this:

2条回答
  •  孤街浪徒
    2021-01-11 19:32

    std::priority_queue is basically a thin layer on top of the heap algorithms. You can easily create your own priority queue with:

    • std::vector
    • std::push_heap
    • std::pop_heap

    Using these building blocks, the implementation is trivial, and you can easily implement a moving pop operation. The following listing contains a minimal, working implementation:

    template >
    class queue
    {
    private:
        std::vector _elements;
        Compare _compare;
    public:
        explicit queue(const Compare& compare = Compare())
            : _compare{compare}
        { }
        void push(Type element)
        {
            _elements.push_back(std::move(element));
            std::push_heap(_elements.begin(), _elements.end(), _compare);
        }
        Type pop()
        {
            std::pop_heap(_elements.begin(), _elements.end(), _compare);
            Type result = std::move(_elements.back());
            _elements.pop_back();
            return std::move(result);
        }
    };
    

提交回复
热议问题