Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

stack

Concept: Stack is an advanced and last out data structure, also known as LIFO(Last in first out). The last element added to the stack will be taken out first, and data will be inserted and removed at the same end of the stack, which is called the “top of the stack”.

Features:

  • Only the top element of the stack can be used by the outside world, so the stack does not allow traversal behavior

  • The data that goes into the stack is called push.

  • The element that pops out of the stack is called a pop.

The constructor

- stack<T> stk; // Stack is implemented using template classes. The default construction of a stack object

- stack<const stack &stack> &stk; // Copy the constructor
Copy the code

The assignment operation

- stack &operator= (const stack &stk); // Override the symbol operator
Copy the code

Data access

- push(elem); // Add elements to the top of the stack

- pop(a);// Remove the first element from the top

- top(a);// Return the top element of the stack
Copy the code

Other operating

- empty(a);// Check whether the stack is empty

- size(a);// Return the stack size

- swap(a);// Swap the elements of two containers
Copy the code

Summary:

- into the stack:push() - Out of stack:pop() - Returns the top element of the stack:top() - Check whether the stack is empty:empty() - Returns the stack size:size(a)Copy the code

“Demo” :

#include <iostream>
#include <stack>

using namespace std;

void test01(a)
{
    // Create a stack container
    stack<int> s;

    // Add elements to the stack (push, push)
    s.push(10);
    s.push(20);
    s.push(30);

    // If the stack is not empty
    while(! s.empty())
    {
        // Outputs the top element of the stack
        cout << "The top element is:" << s.top() << endl;
        // Pop the top element (out of the stack)
        s.pop(a); cout <<"Stack size is:" << s.size() << endl;
        cout << "The top element is:" << s.top() << endl; }}void test02(a)
{
    // Create a stack container
    stack<int> s1;

    // Add elements to the stack (push, push)
    s1.push(10);
    s1.push(20);
    s1.push(30);

    stack<int> s2;
    s2.push(100);
    s2.push(200);
    s2.push(300);

    cout << "Before the exchange" << endl;
    cout << "size of s1 is : " << s1.size(a); cout <<"size of s2 is : " << s2.size(a); s1.swap(s2);
    cout << "After the exchange" << endl;
    cout << "size of s1 is : " << s1.size(a); cout <<"size of s2 is : " << s2.size(a); }int main(a)
{
    test01(a);return 0;
}
Copy the code