关于在C 中实现堆栈的问题

Problem about implementation of a stack in C++

本文关键字:堆栈 问题 实现      更新时间:2023-10-16

我已经解决了有关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的数组。