How is the stack used in C++?
In C++, a stack is a container that stores data and accesses it in Last In, First Out (LIFO) order. The stack can store any type of data, including built-in types (such as int, float) and user-defined types.
The primary operations of stack include:
- push(elem): Add the element elem to the top of the stack.
- pop(): Remove an element from the top of the stack.
- top(): returns the element at the top of the stack without removing it.
- empty(): check if the stack is empty.
- size(): Returns the number of elements in the stack.
Here is a simple example using a stack.
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
std::cout << "Stack size: " << myStack.size() << std::endl;
std::cout << "Top element: " << myStack.top() << std::endl;
myStack.pop();
std::cout << "Stack size: " << myStack.size() << std::endl;
std::cout << "Top element: " << myStack.top() << std::endl;
return 0;
}
Output results:
Stack size: 3
Top element: 30
Stack size: 2
Top element: 20
This example first creates an integer stack (std::stack
Please note that in order to use stack, you need to include the header file