In C++, the stack data structure is implemented using the std::stack
container adapter provided by the Standard Template Library (STL). The std::stack
is a wrapper around other STL container classes, such as std::deque
, std::list
, or std::vector
, but it provides a simplified interface specifically tailored for stack operations.
To use the stack data structure in C++, you need to include the <stack>
header file in your program. Here's an example of how to declare and use a stack:
cpp#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
// Push elements onto the stack
myStack.push(10);
myStack.push(20);
myStack.push(30);
// Check if the stack is empty
if (myStack.empty()) {
std::cout << "Stack is empty.\n";
} else {
std::cout << "Stack is not empty.\n";
}
// Access the top element
std::cout << "Top element: " << myStack.top() << "\n";
// Pop elements from the stack
myStack.pop();
// Access the top element again
std::cout << "Top element after pop: " << myStack.top() << "\n";
// Get the size of the stack
std::cout << "Size of stack: " << myStack.size() << "\n";
return 0;
}
In this example, we create a stack called myStack
using the std::stack<int>
declaration. We then push three elements onto the stack using the push()
function. We check if the stack is empty using the empty()
function and access the top element using the top()
function. After that, we pop an element from the stack using the pop()
function. Finally, we get the size of the stack using the size()
function.
The output of the above program would be:
Stack is not empty.
Top element: 30
Top element after pop: 20
Size of stack: 2
This demonstrates some of the basic operations that can be performed on a stack using the std::stack
container adapter in C++.
Comments
Post a Comment