【发布时间】:2015-06-03 21:50:37
【问题描述】:
我有以下优先级队列:
#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;
}
现在为了获取最后一个元素,我必须 pop() 队列中的所有元素。有什么方法可以让我只检索此优先级队列的最后一个元素。
我知道可以颠倒“CompareTime”中的顺序,以便最后一个元素成为第一个元素。我不想这样做,因为我想按“CompareTime”确定的顺序从优先级队列中弹出()元素。但同时我也想要优先级队列的最后一个元素..而不是从优先级队列中弹出所有元素。是否可以确定优先级队列的最后一个元素的值。
我正在使用以下 gcc 编译器:gcc (Ubuntu/Linaro 4.6.4-6ubuntu2) 4.6.4
【问题讨论】:
-
您想要的不是标准优先级队列的功能/要求。为什么你需要知道这个值/你想用它做什么?作为一个纯粹的理论方面的评论,我注意到你的秒字段显示 0-59:它至少不会在今年夏天的闰秒上中断(今年秒 = 60 一次)。
-
这就是为什么这样存储时间不是一个好主意。
标签: c++ queue priority-queue