关于在C 中实现堆栈的问题
Problem about implementation of a stack in C++
我已经解决了有关C 堆栈的练习。我需要实现一个支持POP((和push((操作的堆栈类。我的输入是一个文件input.txt,其中包含100行。每一行包含2 N元素:第一个是一个字符串,显示该类型,第二个是INT N,显示元素的数量。遵循n个元素。关于输出,元素必须以相反的顺序写入output.txt。通用类型H可以是int,bool,a double和char。n是10到200之间的整数。
示例:
input.txt:
int 5 4 7 8 12 32
char 7 g h t a e d j
double 4 2.78 3.73 4.12 31.92
output.txt:
32 12 8 7 4
j d e a t h g
31.92 4.12 3.73 2.78
我为这个问题写了一个解决方案,汇编成功了,但是当我尝试运行该程序时,终端给了我这个错误:
malloc((:最高尺寸中止
#include <iostream>
#include <fstream>
using namespace std;
template <typename T> class Stack {
private:
int top;
T *arrayStack;
int size;
public:
Stack(int len = 200) {
arrayStack = new T(len);
top = -1;
size = len;
}
void push(T element) {
if(top < size-1) {
top++;
arrayStack[top] = element;
}
else
return;
}
T pop() {
if(top == -1)
return -1;
else {
top--;
return arrayStack[top+1];
}
}
};
int main() {
int intero = 0;
char carattere = '0';
bool booleano = true;
double virgola = 0.00;
ifstream in("input.txt");
ofstream out("output.txt");
int n;
string tipo;
for(int i=0; i<100; i++) {
in >> tipo;
in >> n;
if(tipo == "int") {
Stack<int> pila(n);
for(int i=0; i<n; i++) {
in >> intero;
pila.push(intero);
}
for(int i=0; i<n; i++)
out << pila.pop() << " ";
}
else if(tipo == "char") {
Stack<char> pila(n);
for(int i=0; i<n; i++) {
in >> carattere;
pila.push(carattere);
}
for(int i=0; i<n; i++)
out << pila.pop() << " ";
}
else if(tipo == "bool") {
Stack<bool> pila(n);
for(int i=0; i<n; i++) {
in >> booleano;
pila.push(booleano);
}
for(int i=0; i<n; i++)
out << pila.pop() << " ";
}
else if(tipo == "double") {
Stack<double> pila(n);
for(int i=0; i<n; i++) {
in >> virgola;
pila.push(virgola);
}
for(int i=0; i<n; i++)
out << pila.pop() << " ";
}
out << endl;
}
}
使用new T[len]
代替new T(len)
。
new T(len)
创建一个T
的实例,而T的构造函数将len
作为参数。
new T[len]
用len
元素创建一个T
的数组。
相关文章:
- 算法问题:查找从堆栈中弹出的所有序列
- 堆栈问题(平衡表达式问题集)
- 使用指针计算堆栈问题的大 O 表示法
- 使用泛型类型推送到堆栈时出现问题
- 我的堆栈和库存清单程序的结构有什么问题?
- C++ - 面试问题中的堆栈上的对象
- 在我自己的堆栈中实现top的问题
- 创建堆栈时出现问题!(街机游戏)
- 我遇到了有关递归的堆栈问题
- 关于 std::堆栈推送的分段错误的问题
- C++堆栈内存管理问题
- 在使用 In Order 遍历成员函数时引发异常(堆栈溢出)时出现问题
- 我正在尝试使用回溯来解决 N queen 问题,但在编译时它会给出运行时错误(动态堆栈缓冲区溢出)
- 数组问题:变量周围的堆栈'arr'已损坏
- 关于在C 中实现堆栈的问题
- 未定义对调用堆栈库的引用出现问题
- 我的堆栈中的弹出方法有什么问题?
- 调试堆栈损坏问题
- 我的矩阵堆栈实现(OpenGL ES 2.0)有什么问题
- 使用快速英特尔随机生成器(SSE2)会因堆栈问题而失败..已损坏