栈和队列所用的容器默认都为deque,这种容器可以看作是一种vector和list的中间性能容器。
而deque虽然头插、尾插效率很好,且支持 [ ] 访问(默认容器为它的原因),但是
他的缺点也很明显:
1.中间插入删除会很麻烦
2.[ ]访问的效率不够极致
实现基本上是deque容器的复用:
// stack.h
#pragma once
#include<iostream>
#include<deque>
#include <vector>using namespace std;namespace YC
{//template<class T>//class stack//{//private:// T* _a;// int _top;// int _capacity;//};template<class T, class Container = deque<T>>class stack{public:void push(const T& x){_con.push_back(x);}void pop(){_con.pop_back();}size_t size(){return _con.size();}bool empty(){return _con.empty();}const T& top(){return _con.back();}private:Container _con;};void test_stack1(){YC::stack<int> st;st.push(1);st.push(2);st.push(3);st.push(4);while (!st.empty()){cout << st.top() << " ";st.pop();}cout << endl;}
}
// queue.h
#pragma once
#include<iostream>
#include<deque>
#include <vector>using namespace std;namespace YC
{template<class T, class Con = deque<T>>class queue{public:void push(const T& x){_c.push_back(x);}void pop(){_c.pop_front();}T& back(){return _c.back();}T& front(){return _c.front();}size_t size() const{return _c.size();}bool empty() const{return _c.empty();}private:Con _c;};void test_queue1(){queue<int> q;q.push(1);q.push(2);q.push(3);q.push(4);while (q.size()){cout << q.front() << ' ';q.pop();}cout << endl;}
}