在代码中,我有一个按waitTime
排序的Events
队列。我想找出当前时刻应该执行哪些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<’?
P.S
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);
};
<=
实现<
似乎非常可疑,通常这两者会强制施加不同的排序。 - 463035818_is_not_a_numberwaitTime <= currentTime
不是一个严格的弱排序,因此该代码的行为未定义。问题在于当waitTime
等于currentTime
时,operator<
会同时报告waitTime
在currentTime
之前和currentTime
在waitTime
之前的情况。 - Pete Becker