
481 views
C++ Stack
The C++ stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed. Stacks are often used in various programming tasks, such as function call management (the call stack), expression evaluation, and more.
You can use std::stack in the C++ Standard Library to work with stacks. Here’s how to use it:
C++
#include <iostream>
#include <stack>
int main() {
// Create a stack of integers
std::stack<int> myStack;
// Push elements onto the stack
myStack.push(10);
myStack.push(20);
myStack.push(30);
// Access the top element (the last element added)
std::cout << "Top element: " << myStack.top() << std::endl;
// Pop elements (remove the top element)
myStack.pop();
// Check if the stack is empty
if (myStack.empty()) {
std::cout << "Stack is empty." << std::endl;
} else {
std::cout << "Stack is not empty." << std::endl;
}
// Get the size of the stack
std::cout << "Stack size: " << myStack.size() << std::endl;
return 0;
}In this example:
- We include the
<stack>header to usestd::stack. - We create a stack of integers (
std::stack<int>). - Elements are pushed onto the stack using the
pushfunction. - The
topfunction allows us to access the top (most recently added) element without removing it. - We use the
popfunction to remove the top element from the stack. emptychecks whether the stack is empty.sizereturns the number of elements in the stack.
std::stack provides a simple and convenient way to work with stacks in C++. It abstracts away the underlying data structure (usually a deque) and offers essential stack operations. Stacks are useful in various algorithms and scenarios where you need to maintain a last-in, first-out order of elements.