队列
队列(queue)是程序语言中的一种基本数据结构,顾名思义,遵循先进先出(FIFO)原则,即先进入队列的元素将被先取出。在C++中,可以使用STL(标准模板库)中的队列容器来实现队列。队列容器提供了一种高效的实现方法,可以自动管理队列的大小和元素的添加和删除。
#include <iostream>
#include <queue>
using namespace std;
int main() {
// 创建一个整数队列
queue<int> q;
// 在队列中添加元素
q.push(10);
q.push(20);
q.push(30);
// 输出队列中的元素
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
优先队列
优先队列(priority queue)是一种特殊的队列,它允许您根据元素的优先级对元素进行排序。优先队列可以被视为一个堆,具有在插入和弹出元素时自动调整元素顺序的能力,因此最高优先级的元素始终在队列的前面。可以使用STL中的‘priority_queue'
容器来实现优先队列。
#include <iostream>
#include <queue>
using namespace std;
int main() {
// 创建一个整数优先队列
priority_queue<int> pq;
// 在优先队列中添加元素
pq.push(20);
pq.push(10);
pq.push(30);
// 输出优先队列中的元素
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
return 0;
}
基于自定义cmp规则的优先队列
虽然STL库中提供了基本类型(int,float,double)的优先队列,但是实际编程过程中常常遇到实现对自定义对象的有限队列,这时候就需要自己编写比较规则,例如实现对pair类型的优先队列,优先比较first,first相同则再比较second。
#include<bits/stdc++.h>
using namespace std;
struct cmp
{
bool operator() (const pair<int,string> p1,const pair<int,string> p2)
{
if(p1.first==p2.first) return p1.second>p2.second; //first相同,则second小的先出;
else return p1.first < p2.first; //first大的先输出;
}
};
int main(){
priority_queue<pair<int,string>,vector<pair<int,string> >,cmp> A;
int n;
cin>>n;
for(int i=0;i<n;i++){
string a;
int b;
cin>>a>>b;
pair<int,string>c(b,a);
A.push(c);
}
for(int i=0;i<n;i++){
cout<<A.top().second<<" "<<A.top().first<<endl;
A.pop();
}
return 0;
}