The C++ standard library
In C++, the standard library provides a variety of containers and algorithms to help developers write programs more efficiently.
is part of the C++ Standard Template Library (STL); it implements a Last In First Out (LIFO) data structure. This data structure is very suitable for scenarios where "the last added element is removed first."
The container adapter provides a stack interface, based on other containers (such as deque or vector). The elements of the stack are arranged linearly, but adding and removing elements is only allowed at one end (the top of the stack).
Basic operations
push(): Add an element to the top of the stack.pop(): Remove the top element of the stack.top(): Return a reference to the top element of the stack without removing it.empty(): Check whether the stack is empty.size(): Return the number of elements in the stack.
Syntax
The following is how to use 's basic syntax:
#include
#include
int main() {
std::stack s;
// Push element onto the stack
s.push(1);
s.push(2);
s.push(3);
// Access the top element of the stack
std::cout << "Top element is: " << s.top() << std::endl;
// 移除栈顶元素
s.pop();
std::cout << "After popping, top element is: " << s.top() << std::endl;
// 检查栈是否为空
if (!s.empty()) {
std::cout << "Stack is not empty." << std::endl;
}
// 打印栈的大小
std::cout << "Size of stack: " << s.size() << std::endl;
return 0;
}
Example
Below is an example using complete example, including output results:
Example
#include
#include
int
main
(
)
{
std
::
stack
<
int
s;
// Add elements to the stack
s.
push
(
10
)
;
s.
push
(
20
)
;
s.
push
(
30
)
;
// Print the top element of the stack
std
::
cout
<<
"Top element is: "
<<
s.
top
(
)
<<
std
::
endl
;
// Output: Top element is: 30
// Remove the top element of the stack
s.
pop
(
)
;
std
::
cout
<<
"After popping, top element is: "
<<
s.
top
(
)
<<
std
::
endl
;
// Output: After popping, top element is: 20
// Check whether the stack is empty
if
(
!
s.
empty
(
)
)
{
std
::
cout
<<
"Stack is not empty."
<<
std
::
endl
;
// Output: Stack is not empty.
}
// Print the size of the stack
std
::
cout
<<
"Size of stack: "
<<
s.
size
(
)
<<
std
::
endl
;
// Output: Size of stack: 2
// Continue removing elements
s.
pop
(
)
;
s.
pop
(
)
;
// Check whether the stack is empty
if
(
s.
empty
(
)
)
{
std
::
cout
<<
"Stack is empty."
<<
std
::
endl
;
// Output: Stack is empty.
}
return
0
;
}
Output result:
Top element is: 30
After popping, top element is: 20
Stack is not empty.
Size of stack: 2
Stack is empty.
Notes
does not provide a method to directly access elements in the stack; you can only access them throughtop()to access the top element of the stack.- Attempting to call
top()orpop()on an empty stack will cause undefined behavior. 's underlying container can be any sequence container that supports random access iterators, such asvectorordeque.