Anatomy of std::stack Container Adapter
std::stack
is a container adapter in C++ that provides a Last-In, First-Out (LIFO) data structure, commonly known as a stack. It abstracts away the underlying container implementation, allowing developers to focus on the logical operations of a stack without delving into the details of memory management.
Characteristics:
- LIFO Behavior: Follows the Last-In, First-Out order for elements.
- Adapter Nature: Built on top of other STL containers, such as
std::deque
,std::list
, orstd::vector
.
Creation of std::stack:
Creating a std::stack
involves declaring an instance and specifying the underlying container type, which defaults to std::deque
:
#include <stack>
std::stack<int> myStack; // Default underlying container is std::deque<int>
std::stack<int, std::vector<int>> myVectorStack; // Using std::vector<int> as the underlying container
Functions
1. Element Access Functions:
top():
- Returns a reference to the top element of the stack.
Example:
std::stack<int> myStack;
int topElement = myStack.top();
2. Capacity Functions:
empty():
- Checks if the stack is empty.
Example:
std::stack<int> myStack;
bool isEmpty = myStack.empty();
size():
- Returns the number of elements in the stack.
Example:
std::stack<int> myStack;
size_t sizeOfStack = myStack.size();
3. Modifiers Functions:
push(const T& value):
- Adds an element to the top of the stack.
Example:
std::stack<int> myStack;
myStack.push(42);
pop():
- Returns the top of element from the stack.
Example:
std::stack<int> myStack;
myStack.pop();