priority_queue(优先队列)

优先队列是一个具有权值观念的queue,其内的元素并非依照被推入的次序排列,而是自动按照元素的权值排列,权值最高者,排在最前面。它是一个queue,只允许从底端加入元素,并从顶端取出元素,除此之外别无其它存取元素的途径。

priority_queue以vector为底部容器,加上heap处理规则。为什么这里的queue可以以vector为底部容器呢?vector并不提供pop_front()函数,因为heap的处理规则,大顶堆处理后,把第一个值放在vector的最后一个位置。priority被归类为容器配接器。

template<class T, class Sequence = vector<T>, class Compare = less<typename Sequence::value_type>>
class priority_queue{
public:
    typedef typename Sequence::value_type value_type;
    typedef typename Sequence::size_type size_type;
    typedef typename Sequence::reference reference;
    typedef typename Sequence::const_reference const_reference;

    priority_queue() : c() {}
    explicit priority_queue(const Compare& x) : c(), comp(x) {}

    template<class InputIterator>
    priority_queue(InputIterator first, InputIterator last, const Compare& x):c(first, last), comp(x){
        make_heap(c.begin(), c.end(), comp);
    }
    template<class InputIterator>
    priority_queue(InputIterator first, InputIterator last):c(first, last){
        make_heap(c.begin(), c.end(), comp);
    }
    bool empty() const { return c.empty(); }
    size_type size() const { return c.size(); }
    const_reference top() const { return c.front(); }   //比queue多的函数,查看堆顶元素
    void push(const value_type& x) {
        __STL_TRY {
            c.push_back(x);
            push_heap(c.begin(), c.end(), comp);
        }
        __STL_UNWIND(c.clear());
    }
    void pop() {
        __STL_TRY {
            pop_heap(c.begin(), c.end(), comp);
            c.pop_back();
        }
        __STL_UNWIND(c.clear());
    }
protected:
    Sequence c;
    Compare comp;

};    

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top