Datenstrukturen in c++: Stack

Words
38
Reading
1 min
Listen
Play
5y

Ein Stapelspeicher (Stack) folgt dem Prinzip First-In-Last-Out, also das erste Element was eingefügt wird, wird als letzes wieder entfernt. In diesem Beispiel versuche ich die Funktionsweise eines Stacks mithilfe eines Tasks zu erläutern.

Für mehr Theorie zu Stacks: @ozelot47/datenstrukturen-stack-stapelspeicher

cpp_stack.png

#include 
#include 

class Task {
public:
    int id;
    explicit Task(int id) : id(id) { }
    void doIt(){
        std::cout << "Task-ID: " << id << "\n";
    }
};

void stack(){
    /* like lists, elements will be stacked on the "top"
       so called: FILO (First In Last Out)*/
    std::stack<Task> container;

    /* add 3 tasks */
    container.push(Task(1));
    container.push(Task(2));
    container.push(Task(3));

    /* consume all tasks from the stack */
    while(!container.empty()) {
        Task &task = container.top();
        task.doIt();
        container.pop();
    }
}

int main(){
    stack();
    return 0;
}