一、作业
(将昨天的作业修改为标准模板类的)
1、代码
#include <iostream>
#include <stack>
using namespace std;
//队列模板类
template<typename T>
class Queue
{
private:int max; //队列最大容量int num; //队列内元素数T *ptr; //容器
public:Queue():max(20),num(0){ptr = new T[this->max];cout<<"无参构造"<<endl;}~Queue(){delete [] ptr; //释放空间cout<<"析构函数"<<endl;}Queue(Queue &q):max(q.max),num(q.num),ptr(new T(*q.ptr)) //深拷贝{cout<<"拷贝构造函数"<<endl;}T front(){if(empty()){cout<<"队列为空无法返回"<<endl;T a;return a;}return ptr[0];}T back(){if(empty()){cout<<"队列为空无法返回"<<endl;T a;return a;}return ptr[num-1];}bool empty(){return num==0;}int size(){return num;}void push(T n){//判满if(num>=max){cout<<"容器已满无法继续加入"<<endl;return;}this->num++;this->ptr[num-1] = n;cout<<"添加完毕"<<endl;}void pop(){//判空if(empty()){cout<<"容器为空无法删除"<<endl;return;}for(int i=0;i<this->num;i++){this->ptr[i]=this->ptr[i+1];}this->num--;cout<<"删除完毕"<<endl;}void show(){for(int i=0;i<num;i++){cout<<ptr[i]<<" ";}cout<<endl;}
};
int main()
{Queue<string> q;//判空if(q.empty()){q.push("hhh");q.push("I");q.push("have");q.push("a");q.push("dog");q.show();}cout<<q.back()<<endl;cout<<q.front()<<endl;cout<<q.size()<<endl;q.pop();q.show();return 0;
}
#include <iostream>using namespace std;template<typename T>
class Stack //定义一个栈的模板类
{
private:T *ptr; //栈int num; //栈顶元素数int max; //栈的空间初始大小
public:Stack():num(-1),max(20){ptr = new T[max]; //申请空间cout<<"无参构造"<<endl;}Stack(int t,int m):num(t),max(m){ptr = new T[max]; //申请栈空间for(int i=0;i<num+1;i++){cout<<"请输入第"<<i+1<<"个元素内容为:";cin>>ptr[i];}cout<<"有参构造"<<endl;}~Stack(){delete [] ptr;cout<<"析构函数"<<endl;}Stack(Stack &s):ptr(new T(*s.ptr)),num(s.num),max(s.max){cout<<"拷贝构造函数"<<endl;}//栈顶元素访问T top(){return ptr[num];}//判空bool empty(){return num==-1;}//元素数int size(){return num+1;}//向栈顶插入元素void push(T n){//判满if(num==max-1){cout<<"无法继续插入"<<endl;return;}++this->num;this->ptr[num] = n;}//删除栈顶元素void pop(){//判空if(empty()){return;}this->num--;}void show(){for(int i=0;i<num+1;i++){cout<<ptr[i]<<" ";}cout<<endl;}
};
int main()
{Stack<string> s1(4,10); //有参构造s1.show();s1.pop();s1.show();string buf;cout<<"请输入要尾插的内容:";cin>>buf;s1.push(buf);s1.show();cout<<s1.size()<<" "<<s1.top()<<endl;return 0;
}
2、运行结果
二、思维导图(Lambda、异常处理、文件操作、线程支持、模板)