#include <iostream>
#include <stdexcept> // 用于抛出异常
using namespace std;
template <typename T, int MAXSIZE>
class Stack {
private:
T data[MAXSIZE]; // 使用数组存储栈元素
int top; // 栈顶指针
public:
Stack() : top(-1) {} // 构造函数,初始化栈顶指针为-1
bool isEmpty() const {
return top == -1; // 判断栈是否为空
}
void push(const T& x) {
if (top == MAXSIZE - 1) { // 判断栈是否已满
cout<<"stack full"<<endl;
}
data[++top] = x; // 先将top加1,再存储元素
}
void pop() {
if (isEmpty()) {
cout<<"stack empty"<<endl;
}
top--; // 弹出栈顶元素,将top减1
}
};
int main() {
Stack<int, 10> s; // 创建一个最大容量为10的int类型栈
try {
s.push(1);
s.push(2);
s.push(3);
} catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
2024/4/29 C++day6
于 2024-04-29 20:51:18 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)