簡體   English   中英

有關在C ++中實現堆棧的問題

[英]Problem about implementation of a stack in C++

我必須解決有關C ++中堆棧的練習。 我需要實現一個Stack類,該類支持pop()和push()操作。 我的輸入是一個文件input.txt,其中包含100行。 每行包含2 + N個元素:第一個是顯示類型的字符串,第二個是int N,顯示元素的數量。 跟隨N個元素。 關於輸出,必須以相反的順序將元素寫入到output.txt中。 通用類型H可以是int,bool,double和char。 N是10到200之間的整數。

例:

input.txt:

整數5 4 7 8 12 32

char 7 ghtaedj

雙倍4 2.78 3.73 4.12 31.92

output.txt:

32 12 8 7 4

jdeathg

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]創建的陣列Tlen元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM