优先队列(priority_queue)定义在头文件< queue > 中,可以用来实现二叉堆(大顶堆、小顶堆),主要使用包括对于基本类型和自定义类型的排序,顶部元素(优先级最高/最低)访问,出队、入队等操作。
- 对于基本类型,可以修改默认排序规则,将大顶堆该为小顶堆。
- 对于自定义数据类型,可以创建操作符重载函数(重载<符号),或者自定义比较函数(重载()符号),用于自定义类型的比较操作。
接下来给出优先队列的基本使用:
test_01() : 使用int类型
test_02(): 使用string类型
test_03(): 使用自定义类型struct student
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
// 优先队列:基本数据类型的使用 - int
void test_01()
{
// 默认为大顶堆
priority_queue<int> p1;
p1.push(10);
p1.push(-10);
p1.push(100);
cout << "p1 list 大顶堆(int): ";
while (p1.size())
{
cout << p1.top() << " ";
p1.pop();
}
cout << endl;
// 改为小顶堆实现
priority_queue<int, vector<int>, greater<int>> p2;
p2.push(10);
p2.push(-10);
p2.push(100);
cout << "p2 list 小顶堆(int): ";
while (p2.size())
{
cout << p2.top() << " ";
p2.pop();
}
cout << endl;
}
// 优先队列:基本数据类型的使用 - string
void test_02()
{
// 默认为大顶堆: C B A
priority_queue<string> p3;
p3.push("A");
p3.push("B");
p3.push("C");
cout << "p3 list 大顶堆(string): ";
while (p3.size())
{
cout << p3.top() << " ";
p3.pop();
}
cout << endl;
// 改为小顶堆实现:A B C
priority_queue<string, vector<string>, greater<string>> p4;
p4.push("C");
p4.push("B");
p4.push("A");
cout << "p4 list 小顶堆(string): ";
while (p4.size())
{
cout << p4.top() << " ";
p4.pop();
}
cout << endl;
}
// 优先队列:自定义数据类型的使用 - struct
struct student
{
int score;
string name;
int student_number;
// 重载 < 运算符,用于优先级比较, 以成绩来排名
bool operator<(const student& s) const
{
return this->score < s.score; // 大顶堆
}
student(int s, string n, int sn) :score(s),name(n),student_number(sn){}
};
// 自定义比较函数
struct student_compare_score_greater
{
bool operator() (const student& a, const student& b)
{
return a.score > b.score; // 小顶堆
}
};
void test_03()
{
student s1(89, "wang", 1001001);
student s2(76, "Li", 1001721);
student s3(100, "Zhao", 1001321);
priority_queue<student> p5;
p5.push(s1);
p5.push(s2);
p5.push(s3);
cout << "p5 list 大顶堆(student): " << endl << endl;
while (p5.size())
{
cout << p5.top().name << " " << p5.top().score << " " << p5.top().student_number << endl;;
p5.pop();
}
cout << endl;
// 改为成绩由低到高
priority_queue<student, vector<student>, student_compare_score_greater> p6;
p6.push(s1);
p6.push(s2);
p6.push(s3);
cout << "p6 list 小顶堆(student): " << endl;
while (p6.size())
{
cout << p6.top().name << " " << p6.top().score << " " << p6.top().student_number << endl;;
p6.pop();
}
cout << endl;
}
int main()
{
// int
test_01();
cout << endl;
// string
test_02();
cout << endl;
// struct
test_03();
return 0;
}
运行结果如下:
p1 list 大顶堆(int): 100 10 -10
p2 list 小顶堆(int): -10 10 100
p3 list 大顶堆(string): C B A
p4 list 小顶堆(string): A B C
p5 list 大顶堆(student):
Zhao 100 1001321
wang 89 1001001
Li 76 1001721
p6 list 小顶堆(student):
Li 76 1001721
wang 89 1001001
Zhao 100 1001321
谢谢阅读