重载操作符时出现错误:没有匹配的“operator<”操作符。

3

在代码中,我有一个按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);
};

什么是endTime? - Jake Freeman
“Event” 被定义为什么? - max66
3
请提供一个 [mcve],而不是零散的代码片段。"mcve" 意为“最小可复现示例”,即包含足够信息以重现问题的最小代码示例。 - Richard Critten
顺便提一下,你使用 <= 实现 < 似乎非常可疑,通常这两者会强制施加不同的排序。 - 463035818_is_not_a_number
2
请注意,一旦您将此内容编译成功,仍存在一个严重的问题:waitTime <= currentTime不是一个严格的弱排序,因此该代码的行为未定义。问题在于当waitTime等于currentTime时,operator<会同时报告waitTimecurrentTime之前和currentTimewaitTime之前的情况。 - Pete Becker
我已经对问题进行了修改。 - Kenenbek Arzymatov
3个回答

3

考虑到这个错误消息:

错误:无法匹配‘operator<’(操作数类型分别为‘const double’和‘Event’)

您需要声明运算符。

bool operator<(const double &, const Event &);

看起来算法中使用了条件

currentTime < *it

另一种方法是像这样调用算法:
std::vector<Event>::iterator up = std::upper_bound(queue.begin(), 
                                                   queue.end(), 
                                                   Event { 0.0, currentTime, 0.0 });

这可以通过将currentTime强制转换为Event对象来完成,因为已经为Event对象重载了运算符<。

bool operator<(const Event& otherEvent) const;

2

2
bool Event::operator<(const double& currentTime) const

定义小于运算符仅适用于以下情况:
Event e;
//...
double d = /*...*/;
bool result = e < d;

不是以下情况。
bool result = d < e;

定义这些运算符时,必须双向定义!最好将它们都定义为非成员函数。
bool operator<(const Event& e, const double& currentTime);
bool operator<(const double& currentTime, const Event& e);

为什么要使用非成员函数?为了改善封装性
John Lakos在他的精彩的CPPcon演讲中也这样说到。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接