您的当前位置:首页正文

9优先队列(priority_queue)

2024-11-24 来源:个人技术集锦

1、priority_queue概述

priority_queue是一个拥有权值观念的queue,它允许加入新元素、移除旧元素、审视元素值等功能。由于这是一个queue,所以只允许在底部加入元素,并从顶端取出元素,除此之外别无其他存取元素的途经。priority_queue带有权值观念,其内的元素并非依照被推入的次序排列,而是自动依照元素的权值排列,权值最高者,排在最前面。

priority_queue是利用heap完成,heap是一个以vector表现的完全二叉树。priority_queue是以heap为底部容器完成所有工作,所以priority_queue是配接器(adapter)。priority_queue不提供遍历功能,也不提供迭代器。

template <class T, class Sequence = vector<T>,
          class Compare = less<typename Sequence::value_type> >
template <class T, class Sequence, class Compare>
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;
protected:
  Sequence c;
  Compare comp;
public:
  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); }
  priority_queue(const value_type* first, const value_type* last,
                 const Compare& x) : c(first, last), comp(x) {
    make_heap(c.begin(), c.end(), comp);
  }
  priority_queue(const value_type* first, const value_type* 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(); }
  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());
  }
};

 

显示全文