szablony stos c++

0

Witam mam problem z szablonem jak zrobić żeby działał dla takiego main-a

int main(){

    Stack<double> stack;
    for (index = 0; index < 100000;) {
        stack.push((double)std::rand() / RAND_MAX); }
    bool result = stack.empty();
}

i nie wywalało:

terminate called after throwing an instance of 'St9bad_alloc'
what(): std::bad_alloc

szablon:

#include <iostream>
using namespace std;

template <typename type>
class Stack {

    struct Element {
        type value;
        Element* prev;
    } * tail;

public:
    Stack()
    {
        tail = NULL;
    };

    void push(type val)
    {
        struct Element* e = new Element;
        e->value = val;
        e->prev = tail;
        tail = e;
    };

    type pop()
    {
        if (tail == NULL) {
        }
        else {
            type a = tail->value;
            struct Element* tmp = tail->prev;
            tail = NULL;
            delete tail;
            tail = tmp;
            return a;
        }
    };

    bool const empty()
    {
        if (tail == NULL) {
            return true;
        }
        else {
            return false;
        }
    };

    ~Stack()
    {

        while (tail != NULL) {
            this->pop();
        }
    }
};
1

Kompiluj na 64 bitach i miej więcej ramu.

for (index = 0; index < 100000;)

Wystarczy że zamienisz pętlę nieskończoną na taką skończoną.

Dlaczego implementujesz stos na liście jednokierunkowej? Tzn to jest poprawne, ale wydaje się średnio sensowne tbh.

2
            tail = NULL;
            delete tail;

Hmm...

1 użytkowników online, w tym zalogowanych: 0, gości: 1