Article Directory
1 Basic concepts of stack
Features : The stack stack
is a first-in -last-out ( FILO
First In Last Out) data structure, and only the top end of the stack can insert or delete data.
Stack top element :, only the top element top()
in the stack can be accessed and used by the outside world, soStack does not allow traversal behavior.
Push/Push the stack :, push()
push the element to the top of the stack. Pop
/pop the stack :, pop()
pop the element from the top of the stack.
2 Stack common interface
Note: When using the stack container, you need to include the header file
#include <stack>
.
Constructor :
① stack<T> stk;
: Default no-argument constructor, implemented by class template .
② stack(const stack &stk);
: Copy constructor, use the existing stack object to initialize a new object.
Assignment operation ::
stack& operator=(const stack &stk);
Overload the assignment operator, use the target stack container to assign a value to the current stack container.
Data access ::
push(elem);
Push elements to the top of the stack.
pop();
: Pop the element from the top of the stack.
top();
: Return to the top element of the stack.
Size operation :
empty();
Judge whether the stack is empty.
size();
: Return the size of the stack.
Example : Common interfaces of the stack
#include <iostream>
using namespace std;
#include <stack>
int main() {
//创建stack容器
stack<int> s;
//压栈
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
cout << "当前栈的大小:" << s.size() << endl; //5
while (!s.empty()) {
cout << "当前栈顶元素:" << s.top() << endl; //5→4→3→2→1
//出栈
s.pop();
}
cout << "当前栈的大小:" << s.size() << endl; //0
return 0;
}