C++ STL stack (last in first out) stack detailed explanation

Part.I Attention

insert image description here

  • stack<T>The data of the container adapter is LIFOorganized in a (Last in First Out) manner, which can be imagined as a stack of plates on the dining table.
  • header file must be included#include <stack>

Part.II Funciton

Compared with other sequence containers, stackit is a container with a simple storage mechanism and fewer operations. As shown in the figure below, the stack object only has 7 functions.
insert image description here
The following is stacka complete set of operations that a container can provide:

Function name meaning
top() Returns a reference to the top element of the stack, of type T&. If the stack is empty, the return value is undefined.
push(const T& obj) A copy of the object can be pushed onto the top of the stack. push_back()This is done by calling functions of the underlying container .
push(T&& obj) Pushes an object onto the top of the stack by moving it. push_back()This is done by calling the underlying container's function that takes an rvalue reference parameter .
pop() Pops the top element of the stack without returning any value.
size() Returns the number of elements in the stack.
empty() Returns true if there are no elements in the stack.
emplace() Call the constructor with the passed parameters to generate an object on the top of the stack. Similar to push(), call the constructor one less time than
swap(stack<T> & other_stack) Swaps the elements in the current stack with the elements in the argument. The type of elements contained in the parameter must be the same as that of the current stack. There is a special global function swap()available for stack objects.

Part.III Code

The complete code is as follows:

#include <iostream>
#include <iomanip>
#include <stack>

using namespace std;

int main()
{
    
    
    int tmp=0;
    stack<int> stk({
    
    0,1,2,3});  // stack<int> stk;
    stack<int> stk1({
    
    0,1,2,3}); 
    cout<<stk.top()<<endl;
    stk.pop();
    stk.push(4);
    stk.emplace(5);
    cout<<stk.size()<<setw(3)<<stk.top()<<endl;
    stk.swap(stk1);
    cout<<stk.size()<<setw(3)<<stk.top()<<endl;
    getchar();
    return 0;
}

Because the operation is relatively simple, no explanation is given here. Here is the output:

3
5  5
4  3

Guess you like

Origin blog.csdn.net/Gou_Hailong/article/details/128381770