今天,看C++Template的时候看到那人写了一个Stack,于是乎,手痒,自己也写了一个,在拜读了STD文件和C++模板元编程某些小节之后,你们就看到了这篇代码。
经过上述一番经历之后,我重新写了myVector,使之更完善,更加服务于顶层结构,如:myStack
栈没什么写的,大部分精力都放在了重新构建底层容器上,STL里面的功能函数基本都实现了,除了std的各种相关的构造函数实在整不来那么多
测试效果:
#include "E:数据结构myStack.h" #include <iostream> using namespace std; int main(int argc, char* argv[]) { int arr[7]{ 1,3,5,8,7,4,55 }; myVector<int> V{ arr,arr + 7 }; myStack<int> S; myStack<int>S2{ V }; cout << "test 1" << endl << endl; cout << "栈1添加一个元素 10" << endl << endl; S.push(10); cout << "栈1添加一个元素 15" << endl << endl; S.push(15); cout << "栈1顶部元素为:"; cout << S.top() << endl << endl; S.pop(); cout << "弹出栈1顶部元素" << endl << endl; cout << "栈1顶部元素为:"; cout << S.top() << endl << endl; S.pop(); cout << "弹出栈1顶部元素" << endl << endl; cout << "栈1添加元素 10、15" << endl << endl; S.push(5); S.push(12); cout << "交换栈1栈2" << endl << endl; S.swap(S2); cout << "test 2" << endl << endl; cout << "栈1:" << endl; myStack<int>::container_type container = S._Get_container(); for (auto it : container) cout << it << " "; cout << endl << endl; cout << "栈2:" << endl; myStack<int>::container_type container2 = S2._Get_container(); for (auto it : container2) cout << it << " "; cout << endl; }
Template代码:
#ifndef _MY_STACK #define _MY_STACK #include <E:数据结构myVector.h> template<class T, class myContainer = myVector<T> > class myStack { public: //public date-type information used by class design
typedef myStack<T, myContainer> _Mytype; typedef myContainer container_type; typedef typename myContainer::value_type value_type; typedef typename myContainer::size_type size_type; typedef typename myContainer::_pointer _pointer; #define self (*this) public: //basic functions of class myStack() { elems.clear(); } myStack(const _Mytype& rhs) :elems(rhs.elems) { } explicit myStack(const myContainer& _container) :elems(_container) { } _Mytype& operator=(const _Mytype& other) { elems = other.elems; return self; } public: //some operator-loading functions of stack bool operator==(const _Mytype& rhs) { return elems == rhs.elems; } bool operator!=(const _Mytype& rhs) { return elems != rhs.elems; } bool operator<(const _Mytype& rhs) { return elems < rhs.elems; } bool operator>(const _Mytype& rhs) { return elems > rhs.elems; } bool operator<=(const _Mytype& rhs) { return !(self > rhs); } bool operator>=(const _Mytype& rhs) { return !(self < rhs); } public: // main options of stack void push(T const& item) { //尾部添加元素 elems.push_back(item); } void pop() { //将顶部元素删除 if (elems.empty()) throw "myStack<>::pop(): empty stack "; elems.pop_back(); } const T& top()const { //取顶部元素 if (elems.empty()) throw "myStack<>::top(): empty stack "; return elems.back(); } bool empty()const { //判空 return elems.empty(); } void swap(_Mytype& rhs) { //交换数据 elems.swap(rhs.elems); } size_type size()const { //get the size of stack return elems.size(); } const myContainer& _Get_container()const { //Get the container of stack return elems; } private: myContainer elems; }; #endif
感谢您的阅读,生活愉快~