样例:
- void test_stack1()
- {
- //bit::stack<int, list<int>> st;
- //bit::stack<int, vector<int>> st;
- bit::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;
- }
- #include
- namespace bite
- {
- template<class T>
- class stack
- {
- public:
- stack() {}
- void push(const T& x) {_c.push_back(x);}
- void pop() {_c.pop_back();}
- T& top() {return _c.back();}
- const T& top()const {return _c.back();}
- size_t size()const {return _c.size();}
- bool empty()const {return _c.empty();}
- private:
- std::vector
_c; - };
- }
- #include
- namespace bite
- {
- template<class T>
- class queue
- {
- public:
- queue() {}
- void push(const T& x) {_c.push_back(x);}
- void pop() {_c.pop_front();}
- T& back() {return _c.back();}
- const T& back()const {return _c.back();}
- T& front() {return _c.front();}
- const T& front()const {return _c.front();}
- size_t size()const {return _c.size();}
- bool empty()const {return _c.empty();}
- private:
- std::list
_c; - };
- }
那deque是如何借助其迭代器维护其假想连续的结构呢?
- #include<iostream>
- using namespace std;
-
- #include<stack>
- #include<deque>
- #include<algorithm>
-
- void test_op1()
- {
- srand(time(0));
- const int N = 1000000;
-
- deque<int> dq;
- vector<int> v;
-
- for (int i = 0; i < N; ++i)
- {
- auto e = rand() + i;
- v.push_back(e);
- dq.push_back(e);
- }
-
- int begin1 = clock();
- sort(v.begin(), v.end());//排序涉及到遍历数组
- int end1 = clock();
-
- int begin2 = clock();
- sort(dq.begin(), dq.end());
- int end2 = clock();
-
- printf("vector:%d\n", end1 - begin1);
- printf("deque:%d\n", end2 - begin2);
- }
-
-
- 结果:
- vector:1810
- deque:7265
stack的模拟实现
- #include<deque>
- namespace bit
- {
- template<class T, class Con = deque<T>>
- //template<class T, class Con = vector<T>>
- //template<class T, class Con = list<T>>
- class stack
- {
- public:
- stack() {}
- void push(const T& x) {_c.push_back(x);}
- void pop() {_c.pop_back();}
- T& top() {return _c.back();}
- const T& top()const {return _c.back();}
- size_t size()const {return _c.size();}
- bool empty()const {return _c.empty();}
- private:
- Con _c;
- };
- }
queue的模拟实现
- #include
-
- namespace bit
- {
- template<class T, class Con = deque
> - //template
> - class queue
- {
- public:
- queue() {}
- void push(const T& x) {_c.push_back(x);}
- void pop() {_c.pop_front();}
- T& back() {return _c.back();}
- const T& back()const {return _c.back();}
- T& front() {return _c.front();}
- const T& front()const {return _c.front();}
- size_t size()const {return _c.size();}
- bool empty()const {return _c.empty();}
- private:
- Con _c;
- };
- }