0

I implemented the stack via a linked list to practice manual memory work. I want to add initialization like in vector, I know about move and copy constructors, but it doesn't seem to make sense here.

What needs to be defined inside to write like this Stack<int> stack = { 1, 2, 3 }; ?

template <typename T>
class Node {
public:
    Node(T value_) {
        value = value_;
    }
    Node<T>* next = nullptr;
    int value;
};

template <typename T>
class Stack {
public:
    Stack() {}
    void push(T value) {
        if (top == nullptr) {
            top = new Node<T>(value);
        } else {
            auto new_node = new Node<T>(value);
            new_node->next = top;
            top = new_node;
        }
    }
    T pop() {
        if (top == nullptr) {
            throw out_of_range("Stack is empty");
        }
        T result = top->value;
        auto free_space = top;
        top = top->next;
        delete free_space;
        return result;
    }
private:
    Node<T>* top = nullptr;
};
dabdya
  • 78
  • 6
  • 1
    You'd need a constructor that takes a [`std::initializer_list`](https://en.cppreference.com/w/cpp/utility/initializer_list) as parameter – UnholySheep Jan 10 '22 at 18:52
  • 1
    See also this answer: https://stackoverflow.com/questions/16455029/how-to-implement-an-initializer-list-for-user-defined-type-analogus-to-stdve – Joseph Larson Jan 10 '22 at 18:57
  • 1
    sooner or later this will be relevant: https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – 463035818_is_not_an_ai Jan 10 '22 at 19:18

0 Answers0