C++标准库中的栈和队头文件
栈: #include<stack>
队列:#include<queue>
stack:
stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.
The underlying container may be any of the standard container class templates or some other specifically designed container class. The container shall support the following operations:
- empty
- size
- back
- push_back
- pop_back
queue:
queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed into the "back" of the specific container and popped from its "front".The underlying container may be one of the standard container class template or some other specifically designed container class. This underlying container shall support at least the following operations:
- empty
- size
- front
- back
- push_back
- pop_front
定义方式:
栈:stack<int> s;
队列:queue<int> q;
包含函数:
栈:
s.empty() | 如果栈为空返回true,否则返回false |
s.size() | 返回栈中元素的个数 |
s.pop() | 删除栈顶元素但不返回其值 |
s.top() | 返回栈顶的元素,但不删除该元素 |
s.push() | 在栈顶压入新元素 |
队列:
q.empty() | 如果队列为空返回true,否则返回false |
q.size() | 返回队列中元素的个数 |
q.pop() | 删除队列首元素但不返回其值 |
q.front() | 返回队首元素的值,但不删除该元素 |
q.push() | 在队尾压入新元素 |
q.back() | 返回队列尾元素的值,但不删除该元素 |
存入结构体
可以将结构体存入栈或队列中
比如存入栈:
在引入头文件#include<stack>之后:
typedef struct Str
{
int i;
int j;
}Str;
stack<Str> s;
Str str;
Str.i = 0;
S.j = 0;
s.push(str);
也可将栈中的数据返回直接用结构体接收:
str = s.top();