C++ Stacks

C++ Stacks: Last-In, First-Out (LIFO)

A Stack is an incredibly important data structure in computer science. It operates on the LIFO (Last-In, First-Out) principle.

Think of a stack of pancakes: the last pancake you place on top of the stack is the very first one you eat!


1. Stack Operations

The C++ STL provides the <stack> library, which gives you access to the following core methods:

Stack Example

#include <iostream>
#include <stack>
using namespace std;

int main() { stack<string> webHistory;

// User visits three pages webHistory.push("Google.com"); webHistory.push("GitHub.com"); webHistory.push("IntricateDevo.com");

// The top element is the last one visited cout << "Currently viewing: " << webHistory.top() << "\n";

// User clicks the 'Back' button on their browser webHistory.pop();

// Now the top element is GitHub cout << "Went back to: " << webHistory.top() << "\n";

return 0; }


2. Practical Uses of Stacks

Stacks are used everywhere in software engineering:


Exercise

?

Which principle does a Stack follow?