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

时间:2015-02-22 13:34:59

标签: c++

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

#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

1 个答案:

答案 0 :(得分:0)

我认为没有一个很好的答案。 (显然,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;
}