在STL中,有一类容器完全以底部容器为基础进行实现,这类容器归类为container adapter。
priority_queue
priority_queue默认使用vector为基础,加上heap算法,其实现比较简单。

1 template <class T, class Sequence = vector<T>, 2 class Compare = less<typename Sequence::value_type> > 3 class priority_queue { 4 public: 5 typedef typename Sequence::value_type value_type; 6 typedef typename Sequence::size_type size_type; 7 typedef typename Sequence::reference reference; 8 typedef typename Sequence::const_reference const_reference; 9 protected: 10 Sequence c; 11 Compare comp; 12 public: 13 priority_queue() : c() {} 14 15 template <class InputIterator> 16 priority_queue(InputIterator first, InputIterator last, const Compare& x) 17 : c(first, last), comp(x) { make_heap(c.begin(), c.end(), comp); } 18 19 // 只是对Sequence方法跟heap算法的封装 20 bool empty() const { return c.empty(); } 21 size_type size() const { return c.size(); } 22 const_reference top() const { return c.front(); } 23 void push(const value_type& x) { 24 c.push_back(x); 25 push_heap(c.begin(), c.end(), comp); 26 } 27 void pop() { 28 pop_heap(c.begin(), c.end(), comp); 29 c.pop_back(); 30 } 31 };
stack
stack则默认使用deque为基础,可以通过指定第二个模板参数来指定底部容器。
为什么stack不默认使用vector/list作为底层容器呢?
原因是因为vector在扩容的时候有较差的时间复杂度,而list虽然有平稳的时间复杂度,但是总体平均复杂度较高,
因此折中的使用deque作为stack的底层容器。

1 template <class T, class Sequence = deque<T> > 2 class stack { 3 public: 4 typedef typename Sequence::value_type value_type; 5 typedef typename Sequence::size_type size_type; 6 typedef typename Sequence::reference reference; 7 typedef typename Sequence::const_reference const_reference; 8 protected: 9 Sequence c; 10 public: 11 // 实际上是对Sequence的封装 12 bool empty() const { return c.empty(); } 13 size_type size() const { return c.size(); } 14 reference top() { return c.back(); } 15 const_reference top() const { return c.back(); } 16 void push(const value_type& x) { c.push_back(x); } 17 void pop() { c.pop_back(); } 18 };
queue
queue的实现跟原理跟stack差不多。

1 // STL中list也可以作为其底层容器 2 template <class T, class Sequence = deque<T> > 3 class queue { 4 public: 5 typedef typename Sequence::value_type value_type; 6 typedef typename Sequence::size_type size_type; 7 typedef typename Sequence::reference reference; 8 typedef typename Sequence::const_reference const_reference; 9 protected: 10 Sequence c; 11 public: 12 // 实际上也是对Sequence的封装 13 bool empty() const { return c.empty(); } 14 size_type size() const { return c.size(); } 15 reference front() { return c.front(); } 16 const_reference front() const { return c.front(); } 17 reference back() { return c.back(); } 18 const_reference back() const { return c.back(); } 19 void push(const value_type& x) { c.push_back(x); } 20 void pop() { c.pop_front(); } 21 };