C++ - Stacks Part 1: Introduction to Stacks
A stack is a container adapter that provides restricted access to its elements. You can only push, pop, or peek at the top element.
Examples and Explanation
Basic Stack Declaration
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack; // Creates an empty stack
return 0;
}
Explanation: The std::stack is declared with a specific data type (e.g., int, string). The default underlying container is std::deque.
Adding Elements
myStack.push(10); // Pushes 10 onto the stack
myStack.push(20); // Pushes 20 onto the stack
Explanation: The push() method adds elements to the top of the stack.
Checking Stack Size
std::cout << "Size: " << myStack.size(); // Output: 2
Explanation: The size() method returns the number of elements currently in the stack.