STL queue
最简单的队列,具有着先进先出的特点,与桟不同,桟的特点为先进后出。
在简单算法竞赛中多用于bfs,即广度优先搜索。
这里记录其与一般简单类型,结构体,pair结合使用时的情况。
一般类型
queue<int> Q1;
Q1.push(1);
Q1.push(2);
Q1.push(3);
Q1.push(4);
// 遍历
while (!Q1.empty()) {
int front = Q1.front();
cout << front << endl;
Q1.pop();
}
结构体
struct point {
int x;
int y;
int w;
};
queue<point> Q2;
// 队列与结构体结合
point p;
p.x = 1;
p.y = 3;
p.w = 4;
Q2.push(p);
Q2.push(p);
Q2.push(p);
while (!Q2.empty()) {
point head = Q2.front();
cout << " " << head.x << " " << head.y << " " << head.w;
cout << endl;
// 弹出数据
Q2.pop();
}
pair
queue<pair<int, string> > Q3;
// 队列与pair结合使用
Q3.push(make_pair(1, "one"));
Q3.push(make_pair(2, "two"));
Q3.push(make_pair(3, "three"));
while (!Q3.empty()) {
pair<int, string> p = Q3.front();
cout << p.first << " " << p.second << endl;
Q3.pop();
}
完整测试代码
//
// Created by 29273 on 2021-03-17.
//
#include "bits/stdc++.h"
using namespace std;
struct point {
int x;
int y;
int w;
};
int main() {
queue<int> Q1;
queue<point> Q2;
queue<pair<int, string> > Q3;
// 队列与一般数据结合
Q1.push(1);
Q1.push(2);
Q1.push(3);
Q1.push(4);
// 队列与结构体结合
point p;
p.x = 1;
p.y = 3;
p.w = 4;
Q2.push(p);
Q2.push(p);
Q2.push(p);
// 队列与pair结合使用
Q3.push(make_pair(1, "one"));
Q3.push(make_pair(2, "two"));
Q3.push(make_pair(3, "three"));
// 遍历
while (!Q1.empty()) {
int front = Q1.front();
cout << front << endl;
Q1.pop();
}
while (!Q2.empty()) {
point head = Q2.front();
cout << " " << head.x << " " << head.y << " " << head.w;
cout << endl;
// 弹出数据
Q2.pop();
}
while (!Q3.empty()) {
pair<int, string> p = Q3.front();
cout << p.first << " " << p.second << endl;
Q3.pop();
}
return 0;
}