用c+编写一个栈的类模板,以便于为任何模型的栈提供结构数据操作。并在应用程序中创建整数栈,字符栈和浮点数栈,提供一些数据进行进栈、退栈和打印操作的测试
时间: 2023-11-07 13:09:14 浏览: 43
以下是一个基本的栈类模板的实现,可以用于操作任何类型的数据:
```
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 栈的最大容量
template <typename T>
class Stack {
private:
T data[MAXSIZE]; // 栈的数据
int topIndex; // 栈顶元素下标
public:
Stack() { // 构造函数
topIndex = -1;
}
void push(T value) { // 入栈操作
if (topIndex < MAXSIZE - 1) {
topIndex++;
data[topIndex] = value;
}
}
T pop() { // 出栈操作
if (topIndex >= 0) {
T value = data[topIndex];
topIndex--;
return value;
} else {
return T();
}
}
void print() { // 打印栈中所有元素
for (int i = topIndex; i >= 0; i--) {
cout << data[i] << " ";
}
cout << endl;
}
};
int main() {
Stack<int> intStack; // 整数栈
Stack<char> charStack; // 字符栈
Stack<float> floatStack; // 浮点数栈
// 整数栈测试
intStack.push(1);
intStack.push(2);
intStack.push(3);
intStack.pop();
intStack.push(4);
intStack.print();
// 字符栈测试
charStack.push('a');
charStack.push('b');
charStack.push('c');
charStack.pop();
charStack.push('d');
charStack.print();
// 浮点数栈测试
floatStack.push(1.1);
floatStack.push(2.2);
floatStack.push(3.3);
floatStack.pop();
floatStack.push(4.4);
floatStack.print();
return 0;
}
```
输出结果:
```
4 2 1
d b a
4.4 2.2 1.1
```
在这个示例中,我们使用了类模板来定义一个通用的栈类,它可以用于存储任何类型的数据。我们创建了三个不同类型的栈对象:整数栈、字符栈和浮点数栈,并对它们进行了一些入栈、出栈和打印操作。