如何在不遍历优先级队列的情况下获取该队列的最后一个元素
How to get last element of priority queue without traversing it
我有以下优先级队列:
#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
std::priority_queue不支持您想要直接执行的操作。请参阅:http://www.cplusplus.com/reference/queue/priority_queue/
当然,您总是可以创建自己的DS,但也有一些库容器可以满足您的需要。
编辑:
您可以考虑使用
std::set
http://en.cppreference.com/w/cpp/container/set
它是有序的,您可以快速访问第一个和最后一个元素,也可以快速删除任何元素。请注意,元素必须是唯一的。如果你不想,你可以使用
std::multiset
这是更灵活的,可以做到这一点。
用于获取两端的元素
std::set::begin
std::set::rbegin
迭代器是可用的。由于集合一直是排序的,因此这些元素是最小元素和最大元素。
希望能有所帮助!
您可以将值存储为某个大值-实际值然后在检索时执行相同的操作,即大值队列(顶部)值。例如。例如,大值=100然后存储56等于4420等于80。。。以及在检索时80作为100-80=20
这就是您可以按照相反的优先级顺序填充队列的方式;)
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- boost::进程间消息队列引发错误
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- Android NDK传感器向事件队列报告奇怪的间隔
- 在 Vulkan Qt 中获取队列系列
- 获取 QInputEvent 在 Qt 4.8 中被放入 QEventLoop 队列时的时间戳
- 获取错误:之前在此处声明的布尔队列的编辑<T>
- C++ std::队列推送弹出两个不同的对象获取第一个对象
- 获取一个简单队列的长度
- 如何获取队列的最小值和最大值
- 如何在不遍历优先级队列的情况下获取该队列的最后一个元素
- 从优先级队列中获取一个unique_ptr
- c++:初始化指针队列时获取segfault