1、使用模板类,实现顺序栈
#include <iostream>
using namespace std;
template<typename T>
class Stack
{
T *data;
T top;
T size;
public:
//构造函数
Stack():size(7)
{
data = new T[size];
top = -1;
cout << "Stack的无参构造" << endl;
}
//析构函数
~Stack()
{
delete []data;
cout << "Stack的析构函数" << endl;
}
//判空
bool stackempty();
//判满
bool stackfull();
//入栈
void push(T data);
//出栈
void pop();
//遍历
void show();
};
//判空
template<typename T>
bool Stack<T>::stackempty()
{
return (this->top == -1);
}
//判满
template<typename T>
bool Stack<T>::stackfull()
{
return (this->top == this->size-1);
}
//入栈
template<typename T>
void Stack<T>::push(T data)
{
if(stackfull())
{
cout << "栈已满" << endl;
return;
}
this->top++;
this->data[this->top] = data;
}
//出栈
template<typename T>
void Stack<T>::pop()
{
if(stackempty())
{
cout << "栈为空" << endl;
return;
}
this->top--;
}
//遍历
template<typename T>
void Stack<T>::show()
{
if(stackempty())
{
cout << "栈为空" << endl;
return;
}
for(int i=this->top;i>=0;i--)
{
cout << this->data[i] << " " ;
}
cout << endl;
}
int main()
{
Stack <int>s;
//判空测试
cout << s.stackempty() << endl;
s.push(25);
s.push(77);
s.push(12);
s.push(46);
//入栈测试
s.push(81);
s.push(3);
s.show();
//出栈测试
s.pop();
s.pop();
//判满测试
cout << s.stackfull() << endl;
//遍历测试
s.show();
return 0;
}
2、写一个char类型的字符数组,对该数组访问越界时抛出异常,并做处理。
#include <iostream>
#include <cstring>
using namespace std;
void fun(char arr[],int i)
{
int len = strlen(arr);
if(i>len)
{
throw char(1);
}
if(i<0)
{
throw char(2);
}
}
int main()
{
char arr[20] = "";
int i = 0;
cout << "输入下标" ;
cin >> i;
try
{
fun(arr,i);
}
catch (char res)
{
if(res == 1)
{
cout << "超过数组大小" << endl;
}
else if(res == 2)
{
cout << "输入的值小于0" << endl;
}
}
return 0;
}
3、整理思维导图