擁有權值的queue,權值最高者永遠排在最前面。priority_queue以vector為底層容器,配合heap的一套泛型算法,就能實現相應功能。
代碼如下:
~~~
template <class T, class Sequence = vector<T>,
class Compare = less<typename Sequence::value_type> >
class priority_queue {
....
protected:
Sequence c; // 底層容器
Compare comp; // 比較標準
....
template <class InputIterator>
priority_queue(InputIterator first, InputIterator last, const Compare& x)
: c(first, last), comp(x) { make_heap(c.begin(), c.end(), comp); } // 將vector變為heap
template <class InputIterator>
priority_queue(InputIterator first, InputIterator last)
: c(first, last) { make_heap(c.begin(), c.end(), comp); } // 將vector變為heap
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); // 先壓入vector
push_heap(c.begin(), c.end(), comp); // 再調整
}
__STL_UNWIND(c.clear());
}
void pop() {
__STL_TRY {
pop_heap(c.begin(), c.end(), comp); // 最大元素放vector尾部
c.pop_back(); // 彈出
}
__STL_UNWIND(c.clear());
}
};
~~~
priority_queue內部代碼很簡單,都是直接調用vector或heap的提供的一些接口。由于priority_queue和queue一樣也具有“先進先出”的性質,所以沒有定義迭代器。
參考:
《STL源碼剖析》 P183.
- 前言
- 順序容器 — heap
- 關聯容器 — 紅黑樹
- 關聯容器 — set
- 關聯容器 — map
- 關聯容器 — hashtable
- 關聯容器 — hash_set
- 關聯容器 — hash_map
- 算法 — copy
- 順序容器 — stack
- 順序容器 — queue
- 順序容器 — priority_queue
- 順序容器 — slist
- construct()和destroy()
- 空間配置器
- 函數適配器
- 迭代器以及“特性萃取機”iterator_traits
- 算法 — partial_sort
- 算法 — sort
- 仿函數
- 適配器(adapters)
- C++簡易vector
- C++簡易list
- STL算法實現
- C++模板Queue