Article Directory
3.5 stack container
3.5.1 Basic concepts of stack
Concept: stack is a first in last out (FILO) data structure, it has only one exit
[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-wslFqw0l-1615015111578)(assets/clip_image002-1547604555425.jpg)]
Only the top element in the stack can be used by the outside world, so the stack does not allow traversal behavior
Data entering the stack is called- stacking push
Popping data from the stack is called-popping pop
The stack in life:
[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-g2bb9e1f-1615015111581)(assets/clip_image002.png)]
[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-8a94Z7GP-1615015111582)(assets/clip_image002-1547605111510.jpg)]
3.5.2 Stack common interfaces
Function description: Commonly used external interface of stack container
Constructor:
stack<T> stk;
//stack is implemented using template classes, the default structure of the stack objectstack(const stack &stk);
//Copy constructor
Assignment operation:
stack& operator=(const stack &stk);
//Overload the equal sign operator
Data access:
push(elem);
//Add elements to the top of the stackpop();
//Remove the first element from the top of the stacktop();
//Return to the top element of the stack
Size operation:
empty();
//Determine whether the stack is emptysize();
//Return the size of the stack
Example:
#include <stack>
//栈容器常用接口
void test01()
{
//创建栈容器 栈容器必须符合先进后出
stack<int> s;
//向栈中添加元素,叫做 压栈 入栈
s.push(10);
s.push(20);
s.push(30);
while (!s.empty()) {
//输出栈顶元素
cout << "栈顶元素为: " << s.top() << endl;
//弹出栈顶元素
s.pop();
}
cout << "栈的大小为:" << s.size() << endl;
}
int main() {
test01();
system("pause");
return 0;
}
to sum up:
- Push to the stack — push
- Pop — pop
- Return to the top of the stack — top
- Determine whether the stack is empty — empty
- Return stack size — size
For more information, please follow the official account: