优先级队列是一种抽象数据类型,它体现了容器的概念,其元素具有附加的“优先级”。最高优先级的元素总是出现在队列的前面。如果该元素被删除,则下一个最高优先级元素前进到前面。
C++标准库定义了一个类模板priority_queue,操作如下:
push:将元素插入优先队列。
top:从优先级队列中返回(不移除)最高优先级元素。
pop:从优先级队列中移除最高优先级的元素。
size:返回优先级队列中的元素个数。
empty:根据优先队列是否为空,返回true或false。
下面的代码sn-p展示了如何构造两个优先级队列,一个可以包含整数,另一个可以包含字符串:
#include <queue>
priority_queue<int> q1;
priority_queue<string> q2;
以下是优先队列使用示例:
#include <string>
#include <queue>
#include <iostream>
using namespace std; // This is to make available the names of things defined in the standard library.
int main()
{
piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.
pq.push("the quick");
pq.push("fox");
pq.push("jumped over");
pq.push("the lazy dog");
// The strings are ordered inside the priority queue in lexicographic (dictionary) order:
// "fox", "jumped over", "the lazy dog", "the quick"
// The lowest priority string is "fox", and the highest priority string is "the quick"
while (!pq.empty()) {
cout << pq.top() << endl; // Print highest priority string
pq.pop(); // Remmove highest priority string
}
return 0;
}
这个程序的输出是:
the quick
the lazy dog
jumped over
fox
由于队列遵循优先级规则,因此字符串从最高优先级到最低优先级打印。
有时需要创建一个优先级队列来包含用户定义的对象。在这种情况下,优先级队列需要知道用于确定哪些对象具有最高优先级的比较标准。这是通过属于重载运算符 () 的类的函数对象来完成的。重载的 () 充当
struct Time {
int h;
int m;
int s;
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
}
根据上述比较标准存储时间的优先级队列将定义如下:
priority_queue<Time, vector<Time>, CompareTime> pq;
Here is a complete program:
#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
struct Time {
int h; // >= 0
int m; // 0-59
int s; // 0-59
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2)
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
};
int main()
{
priority_queue<Time, vector<Time>, CompareTime> pq;
// Array of 4 time objects:
Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};
for (int i = 0; i < 4; ++i)
pq.push(t[i]);
while (! pq.empty()) {
Time t2 = pq.top();
cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
setw(3) << t2.s << endl;
pq.pop();
}
return 0;
}
程序从最晚到最早打印时间:
5 16 13
5 14 20
3 2 40
3 2 26
如果我们希望最早的时间具有最高优先级,我们将像这样重新定义 CompareTime:
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
{
if (t2.h < t1.h) return true;
if (t2.h == t1.h && t2.m < t1.m) return true;
if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
return false;
}
};