C++ STL: Common usage of stack

stack stack

last in first out

The top of the stack pointer always points to a mark on the top element of the stack, usually counted as TOP. When there is no element in the stack (that is, the stack is empty), TOP is -1.

Common uses: stack is used to simulate some recursion to prevent the program from limiting the memory of the stack and causing the program to run incorrectly.

1. The definition of stack

Before using it, you need to add the header file first.

#include <stack>
using namespace std;

Access to elements in the stack container:

Due to the first-in, last-out data structure, the stack in STL can only access the top element of the stack through top().

st.top();

2. Common operations of stack

type type explanation
push stack
top Pop the top element of the stack
pop pop out
empty Empty
size Get the number of elements in the stack

Notice:

  • Before using the pop() function and the top() function, you must first use the empty() function to determine whether the stack is empty.

  • STL does not implement the emptying of the stack, and elements can be repeatedly popped out through the while loop until the stack is empty. as follows:

    while(!st.empty()){
          
          
    	st.pop();
    }
    

1. push()

Push x onto the stack.

st.push(i);

2. top ()

Directly take the value pointed to by the top element TOP of the stack.

st.top();

3. pop ()

Pop the top element of the stack.

st.pop();

4. empty()

Returns true only if the stack is empty if TOP = -1; otherwise, returns false.

if(st.empty() == true){
    
    
  
}

5. size

Returns the number of elements in the stack.

st.size();

Guess you like

Origin blog.csdn.net/qq_41883610/article/details/129913781