在同一优先级队列中创建递增和递减顺序选项
Creating increasing and decreasing order option in the same priority queue?
我创建了一个优先级队列,如下所示:
#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()
{
int order;
cout<<"Enter whether you want to create the priority queue in increasing or decreasing order";
cin>>order;
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;
}
此优先级队列按时间的递增顺序排列。现在,我想给用户一个选项,让他在运行时根据增加的时间还是减少的时间来订购——如示例所示。根据用户提供的选择,我想按递增顺序或递减顺序排列优先级队列。我必须为相同的队列创建一个单独的优先级队列和CompareTime类吗。或者,是否可以使用现有的数据结构来合并此功能?
我使用的是gcc版本:gcc(Ubuntu/Linaro 4.6.3-1ubuntu5)4.6.3
我认为没有一个好的答案。(显然,std::priority_queue
并不是处理此任务的最佳数据结构。我建议使用std::vector
并对其进行排序。)涉及优先级队列的一种可能的解决方案是:
class CompareTimeInverse {
public:
bool operator()(Time& t1, Time& t2)
{
CompareTime c;
return !c(t1, t2);
}
};
template<typename C>
void impl(Time* t, std::size_t t_sz)
{
priority_queue<Time, vector<Time>, C> pq;
for (int i = 0; i < t_sz; ++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();
}
}
int main()
{
int order;
cout<<"Enter whether you want to create the priority queue in increasing or decreasing order";
cin>>order;
// Array of 4 time objects:
Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};
if (order == 0) {
impl<CompareTime>(t, 4);
}
else if (order == 1) {
impl<CompareTimeInverse>(t, 4);
}
return 0;
}
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 为什么不;名字在地图上是按顺序排列的吗
- Win32编译器选项和内存分配
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 数到第n个楼梯的路(顺序无关紧要)
- 优先顺序:智能指针和类析构函数
- 在循环中按顺序遍历成员变量
- 独立读取-修改-写入顺序
- 通过选项卡的文本设置QTabWidget顺序
- 由于选项卡顺序的原因,鼠标光标总是得到错误的hwnd-MFC应用程序
- 将字符指针按顺序存储在 map 中 std::map<char*, int> mymap。将其存储为字符或字符串不是一个选项
- C++嵌套的"命名空间""使用"名称查找首选项顺序
- 在使用C MFC中使用EnableMditAbbedGroup时,如何持久文档选项卡顺序
- AC_LANG_PROGRAM由于链接器选项的顺序失败了链接阶段
- 带有返回键的 Qt 选项卡顺序
- 在同一优先级队列中创建递增和递减顺序选项
- 修复在QT中的布局中插入小部件后的选项卡顺序
- 在对话框中以编程方式更改选项卡顺序的其他方法