在同一优先级队列中创建递增和递减顺序选项

Creating increasing and decreasing order option in the same priority queue?

本文关键字:顺序 选项 创建 优先级 队列      更新时间:2023-10-16

我创建了一个优先级队列,如下所示:

#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;
}