優先隊列(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
謝謝閱讀