-->

C++ - Stacks Part 2: Basic Stack Operations

Stacks provide core operations like adding, removing, and viewing the top element.

Examples and Explanation

Viewing the Top Element

std::cout << "Top: " << myStack.top(); // Output: 20

Explanation: The top() method retrieves the last element added without removing it.

Removing Elements

myStack.pop(); // Removes the top element (20)

Explanation: The pop() method removes the top element but does not return its value.

Emptying the Stack

while (!myStack.empty()) {

    std::cout << myStack.top() << " ";

    myStack.pop();

}

// Output: 10

Explanation: Use the empty() method to check if the stack is empty and iterate over it to clear its contents.