gpt4 book ai didi

c++ - 与 priority_queue 中的第三个变量进行比较,c++

转载 作者:太空狗 更新时间:2023-10-29 21:21:23 26 4
gpt4 key购买 nike

在此页面上:http://comsci.liu.edu/~jrodriguez/cs631sp08/c++priorityqueue.html作者给出了一个在 C++ 中使用优先级队列的很好的例子。在这篇文章中,作者展示了如何连续订购不同的时间。我有一个类似的问题,我想根据与给定时间点的接近程度来排序时间。我的问题是如何向比较器添加第三个输入,以便可以考虑额外的参数。 IE。我们如何使比较器内部的 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;
}

谢谢。

最佳答案

你的比较器本身可以在实例化时被参数化:

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

如果语法不准确,请提前致歉。我现在没有编译器,但我希望这个想法足够清楚。

关于c++ - 与 priority_queue 中的第三个变量进行比较,c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22618376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com