stack, queue of STL

1.Introduction to stack:
stack is a container adapter in STL, designed to operate in the scenario of First In Last Out (FILO) structure, in this case, the insertion and deletion of elements can only be Do it at the end of the container.
Elements can only be popped and pushed from the back of this particular container, which is the top of the stack.
To use stack, you need to declare the header file #include<stack>

2.Construction of stack
Construct satck: default construction form: stack<Type>stkName;
such as:

stack< int>s1;//定义一个存放int的stack容器,并命名为s1
stack<flaoat>s2;//定义一个存放float的容器
stack<string>s3;
//尖括号内还可以设置指针类型或者是自定义类型

3. Basic operation functions of stack

push(x) //入栈操作(加入栈顶),将x加入栈顶
pop()   //出栈操作(删除栈顶),只是出栈,没有返回值
top()   //返回第一个元素(栈顶元素)
size()  //返回栈中的元素个数
empty() //当栈为空时返回true
swap()  //交换两个栈的内容(所有元素)

4. ⚠️ Pop() on an empty stack will cause the program to terminate abnormally, you should use empty() to check in advance

5. Copy construction and assignment of stack

stack对象的拷贝构造形式:stack< Type>stk2(stk1);
stack的赋值形式:stk2 = stk1;
例如:
stack<int>s1;   
stack<int>s2(s1);//拷贝s1并构造s2
stack<int>s3;
s3 = s1;        //将s1的值赋给s3

6. The relational operator of stack
== != > >= < <=
a.== is used to compare whether two stacks are equal. First, determine whether the size is equal, and then use == to determine whether the elements are equal. Stop at the first unequal
b. != and == are the opposite. As long as the size is different or one element is different, it is not equal
c.< is to start the comparison from the first element and stop when it is found not less than, if one stack is the prefix of the other stack, then the long stack is larger, and the remaining 3 types Relational operators work on the same principle.
The return value is both 0 and 1

7.queue introduction:
quene is a container adapter in STL, designed to operate in the context of First In First Out (FIFO) structure, in this case, the insertion of elements is performed at the end of the container. , the deletion is performed at the head of the container.
To use queue, you need to declare the header file #include<queue>

8. The construction of queue (same as stack)
Construct queue: default construction form: stack<Type>stkName;
such as:

stack< int>s1;//定义一个存放int的queue容器,并命名为s1
stack<flaoat>s2;//定义一个存放float的容器
stack<string>s3;
//尖括号内还可以设置指针类型或者是自定义类型

9. The basic operation function of queue

push(x) //入队操作(加入队尾),将x加入队尾
pop()   //出队操作(删除队首),只是出队,没有返回值
//top()返回第一个元素(栈顶元素)
front() //返回第一个元素(队首元素)
back()  //返回最后一个元素(队尾元素)
size()  //返回队列中的元素个数
empty() //当队列为空时返回true
swap()  //交换两个队列的内容(所有元素)

Summary:
Application of stack:
recursive algorithm
Bracket matching detection
DFS algorithm
...
Queue application:
save temporarily unused data (storage address)
BFS algorithm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325861974&siteId=291194637