How to move elements out of STL priority queue

后端 未结 2 950
别跟我提以往
别跟我提以往 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:36

    This is indeed a flaw in std::priority_queue. But you can easily extend it like this:

    template <
        class T,
        class Container = std::vector,
        class Compare = std::less>
    class priority_queue : public std::priority_queue {
    public:
      T top_and_pop() {
        std::pop_heap(c.begin(), c.end(), comp);
        T value = std::move(c.back());
        c.pop_back();
        return value;
      }
    
    protected:
      using std::priority_queue::c;
      using std::priority_queue::comp;
    };
    

    (based on @nosid answer)

提交回复
热议问题