试编写一个栈的类模板(包括其成员函数的实现),以便为任何类型的对象提供栈结构的数据操作。然后在main()实现栈的各种操作。
时间: 2024-03-26 15:35:28 浏览: 23
好的,以下是栈的类模板及其成员函数的实现:
```c++
#include <iostream>
using namespace std;
template <class T>
class Stack {
private:
T* stackArray;
int stackSize;
int top;
public:
Stack(int size) {
stackArray = new T[size];
stackSize = size;
top = -1;
}
~Stack() {
delete[] stackArray;
}
void push(T value) {
if (isFull()) {
cout << "Stack is full!\n";
}
else {
top++;
stackArray[top] = value;
}
}
void pop() {
if (isEmpty()) {
cout << "Stack is empty!\n";
}
else {
top--;
}
}
T peek() const {
if (isEmpty()) {
cout << "Stack is empty!\n";
return T();
}
else {
return stackArray[top];
}
}
bool isFull() const {
return top == stackSize - 1;
}
bool isEmpty() const {
return top == -1;
}
};
int main() {
Stack<int> intStack(5);
intStack.push(10);
intStack.push(20);
intStack.push(30);
cout << "Top of the stack: " << intStack.peek() << endl;
intStack.pop();
intStack.pop();
cout << "Top of the stack: " << intStack.peek() << endl;
intStack.push(40);
intStack.push(50);
while (!intStack.isEmpty()) {
cout << intStack.peek() << " ";
intStack.pop();
}
cout << endl;
Stack<string> stringStack(3);
stringStack.push("Hello");
stringStack.push("World");
cout << "Top of the stack: " << stringStack.peek() << endl;
stringStack.pop();
cout << "Top of the stack: " << stringStack.peek() << endl;
stringStack.push("C++");
while (!stringStack.isEmpty()) {
cout << stringStack.peek() << " ";
stringStack.pop();
}
cout << endl;
return 0;
}
```
在上面的代码中,我们定义了一个模板类`Stack`,它使用类型参数`T`表示栈中存储的元素类型。类中的`stackArray`数组用于存储元素,`stackSize`表示栈的大小,`top`表示栈顶元素的下标。
我们实现了`push`、`pop`、`peek`、`isFull`、`isEmpty`等成员函数,以便为栈提供各种操作。我们还在`main()`函数中演示了如何使用该类模板来创建整数类型和字符串类型的栈,并执行各种操作。
注意,我们使用`new`和`delete[]`来动态分配和释放内存,以确保栈的大小可以在运行时确定。同时,我们还使用`const`在一些成员函数中,以确保它们不会修改类的状态。