在代码中,我有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&lt;'?
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);
};
答案 0 :(得分:3)
考虑此错误消息
错误:'operator&lt;'不匹配(操作数类型是'const double'和 “事件”)
您需要申报运营商
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
类型的对象,因为已经重载了运算符&lt;对于Event
..
bool operator<(const Event& otherEvent) const;
答案 1 :(得分:2)
这可能非常有用。 以下链接涉及全局运算符覆盖及其局限性,以及在C ++ 11中使用 friend 关键字。
[link] Why should I overload a C++ operator as a global function (STL does) and what are the caveats?
答案 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);
(为什么非成员函数?到improve encapsulation)
约翰拉科斯有一个has a wonderful CPPcon talk,他说的确如此。