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!
The C++ STL provides the <stack> library, which gives you access to the following core methods:
.push() - Adds an element to the top of the stack..pop() - Removes the element from the top of the stack..top() - Returns the value of the top element without removing it..empty() - Returns true if the stack is empty..size() - Returns the number of elements in the stack.#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; }
Stacks are used everywhere in software engineering:
Ctrl+Z pops the last action!Which principle does a Stack follow?