栈(stack):
1:先进后出的线性表,并且栈底是封闭的。
2:栈的相关操作如下:
- top() 取出栈顶元素,但是不移出栈中
- empty() 判断栈是否为空
- push() 添加元素到栈顶
- pop() 弹出栈顶元素
- size() 返回栈中的存储元素个数
#include <stdio.h>
#include <stack>
int main(){
std::stack<int> S; //创建以一个栈
if(S.empty()) {
printf("S is empty\n");
}
S.push(5); //进行入栈操作
S.push(3);
printf("S.top = %d\n",S.top());//打印栈顶元素
S.pop(); //将栈顶元素移出
printf("S.top = %d\n",S.top());
S.pop();
S.push(10);
S.push(5);
S.push(4);
printf("S.size = %d\n",S.size());//打印栈中元素个数
}
队列(queue):
1:先进先出的线性表。
2:队列的相关操作如下:
- empty() 判断队列是否为空
- front() 返回队列首部元素
- back() 返回队列尾部元素
- pop() 弹出队列首部元素
- push() 添加元素到队列
- size() 返回队列的存储元素个数
#include <stdio.h>
#include <queue>
int main(){
std::queue<int> S;
if(S.empty()){ //判断队列是否为空
printf("S is empty\n");
}
S.push(1); //将 1 2 3 4 入队列
S.push(2);
S.push(3);
S.push(4);
printf("S.front = %d\n",S.front()); //打印队首元素 1
S.pop(); //删除队首元素 1
printf("S.back = %d\n",S.back()) ; //打印队尾元素 4
printf("S.size = %d\n",S.size()); //输出队列中存储元素的个数
for(;!S.empty();){ //输出队列中剩余元素
printf("%d\n",S.front());
S.pop();
}
}
优先级队列:
1: 与队列类似,但是按照一定的优先级从小到大(或者从大到小),出队列选择优先级大的
2:优先级队列相关操作:
- empty() 判断优先级队列是否为空
- top() 返回优先级最大的元素
- pop() 弹出优先级队列首部元素
- push() 添加元素到优先级队列
- size() 返回优先级队列的存储元素个数
#include <stdio.h>
#include <queue>
int main(){
std::priority_queue<int> Big_heap; // 默认创建一个大优先级队列
std::priority_queue<int , std::vector<int> , std::greater<int> > Small_heap; //构建一个小优先级队列
std::priority_queue<int , std::vector<int> , std::less<int> > Big_heap2; //构建一个优先级队列
if(Big_heap.empty()){ //判断优先级队列是否为空
printf("Big_heap is empty\n");
}
int test[] = {10 , 45 , 1 , 7 , 20 , 5 };
for(int i = 0; i < 6 ; i++){
Big_heap.push( test[i] );
}
printf("Big_heap.top = %d\n", Big_heap.top() ); //取出优先级最大的元素
Big_heap.pop(); //移除优先级最大的元素
printf("Big_heap.size = %d\n", Big_heap.size() ); //计算优先级队列中的元素个数
}