在此页面上:http://comsci.liu.edu/~jrodriguez/cs631sp08/c++priorityqueue.html 作者给出了在c ++中使用优先级队列的一个很好的例子。在此,作者展示了如何连续订购各种时间。我有一个类似的问题,我想根据与给定时间点的接近程度来订购时间。我的问题是如何向比较器添加第三个输入,以便可以考虑额外的参数。即我们如何才能使比较器中的t3成为从外部传递的变量。
#include <iostream>
#include <queue>
#include <iomanip>
#include <cstdlib>
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)
{
Time t3 = {{2,9,0}};
if (abs(t3.h - t2.h) > (t3.h - t1.h))
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;
}
感谢。
答案 0 :(得分:2)
您的比较器本身可以在实例化时进行参数化:
class CompareTime
{
Time t;
public:
CompareTime(const Time& arg) : t{arg} {}
bool operator()(const Time& t1, const Time& t2) const
{
return (abs(t.h - t2.h) > abs(t.h - t1.h));
}
};
声明如下:
Time myTime; // modify to your leisure...
// ...then create your queue with myTime as the fixed param
priority_queue<Time, vector<Time>, CompareTime> pq{CompareTime{myTime};
如果语法不是正确的话,请提前道歉。我现在没有编译器,但我希望这个想法足够清楚。
答案 1 :(得分:1)
最后,通过WhozCraig和user783920的有用指示,以下解决方案似乎有效。
#include <iostream>
#include <queue>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct Time {
int h; // >= 0
int m; // 0-59
int s; // 0-59
};
class CompareTime
{
Time t;
public:
CompareTime(const Time& arg) {
std::cout << "struct constructor \n";
t=arg;
}
// CompareTime(){}
bool operator()(const Time& t1, const Time& t2) const
{
return (abs(t.h - t2.h) > abs(t.h - t1.h));
}
};
int main()
{
Time mytime ={0};
mytime.h=6;
priority_queue<Time, vector<Time>, CompareTime> pq{CompareTime(mytime)};
// Array of 4 time objects:
Time t[4] = { {3, 2, 40}, {2, 2, 26}, {5, 16, 13}, {1, 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;
}