Datenstrukturen in c++: Stack

avatar

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: https://peakd.com/hive-196387/@ozelot47/datenstrukturen-stack-stapelspeicher

cpp_stack.png

#include <iostream>
#include <stack>

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;
}


0
0
0.000
2 comments
avatar

Vielen Dank für deinen Einsatz :)

Solche Fachartikel braucht die Blockchain

0
0
0.000