【发布时间】:2018-05-15 15:05:00
【问题描述】:
在代码中,我有Events 的队列,按waitTime 排序。我想找出当前应该执行哪个Events,所以我这样做:
std::vector<Event>::iterator up = std::upper_bound(queue.begin(), queue.end(), currentTime);
如果我重载 < 运算符,std::upper_bound 将起作用:
bool Event::operator<(const double& currentTime) const
{
return waitTime < currentTime;
}
但我有一个错误:
error: no match for ‘operator<’ (operand types are ‘const double’ and ‘Event’)
我应该如何正确地重载'operator
附言
class Event{
public:
double startTime;
double waitTime;
double size;
Event(double start, double wait, double size);
bool operator<(const Event& otherEvent) const;
bool operator<(const double& currentTime) const;
bool operator() (const Event & event, const double & right);
};
【问题讨论】:
-
什么是 endTime?
-
而
Event被定义为...? -
请发minimal reproducible example,不要乱码。
-
顺便说一句,您使用
<=来实现<看起来非常可疑,通常这两个强加完全不同的顺序 -
请注意,一旦你得到这个编译,还有一个严重的问题:
waitTime <= currentTime不是严格的弱排序,所以代码的行为是未定义的。问题是当waitTime等于currentTime时,operator<报告 bothwaitTime出现在currentTime之前 并且currentTime出现在waitTime之前。
标签: c++ c++11 vector casting operator-overloading