C++复习栈和队列
栈stack
- 先进后出
- 头文件<stack>
- stack<int>s;
- 基本操作
- 入栈——s.push(a);
- 出栈——s.pop();
- 返回大小——s.size();
- 是否为空——s.empty();
- 返回栈顶——s.top();
队列queue
-
先进先出
- 头文件<queue>
- queue<int>q;
- 基本操作
- 入队——q.push(a);
- 出队——q.pop();
- 返回大小——q.size();
- 是否为空——q.empty();
- 返回队首——q.front();
- 返回队尾——q.back();
优先队列
- 内部有序
- 头文件<queue>
- priority_queue<int>q;
- 基本操作
- q.push(a);
- q.pop();
- q.top();
- q.size();
- q.empty();
- 使用
-
#include<queue> #include<iostream> #include<algorithm> using namespace std; struct cmp{ operator ()(string &a,string &b){ if(a[0] != b[0])return a[0] < b[0]; else return a > b; } }; //运算符重载 struct student{ int grade; string name; friend bool operator < (student a, student b){ return a.grade > b.grade; } }; int main(){ priority_queue<int>q; //大的优先 priority_queue<int,vector<int>,greater<int> >q; //小的优先 //自定义优先级 priority_queue<string,vector<string>,cmp>q; //结构体 student s[4] = { {67,"Kite"}, {59,"Tom"}, {100,"Jim"}, {98,"Mark"} }; priority_queue<student>q; return 0; }
浙公网安备 33010602011771号