3

In code I have queue of Events sorted by waitTime. I want to find which Events should be executed for the current moment, so I do this:

std::vector<Event>::iterator up = std::upper_bound(queue.begin(), queue.end(), currentTime);

The std::upper_bound will work if I overload < operator:

bool Event::operator<(const double& currentTime) const
{
    return waitTime < currentTime;
}

But I have an error:

   error: no match for ‘operator<’ (operand types are ‘const double’ and ‘Event’)

How should I correctly overload ‘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);
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Kenenbek Arzymatov
  • 8,439
  • 19
  • 58
  • 109

3 Answers3

3

Taking into account this error message

error: no match for ‘operator<’ (operand types are ‘const double’ and ‘Event’)

you need to declare the operator

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

It seems that within the algorithm there is used the condition

currentTime < *it

Another approach is to call the algorithm like

std::vector<Event>::iterator up = std::upper_bound(queue.begin(), 
                                                   queue.end(), 
                                                   Event { 0.0, currentTime, 0.0 });

that is by using casting of currentTime to an object of the type Event because there is already overloaded operator < for objects of the type Event..

bool operator<(const Event& otherEvent) const;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

This might be really useful. The following link deals with global operator overrides, and the limitations thereof, as well as the use of the friend keyword in C++ 11.

[link] Why should I overload a C++ operator as a global function (STL does) and what are the caveats?

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

Defines the less-than operator for only the following situation:

Event e;
//...
double d = /*...*/;
bool result = e < d;

NOT the following situation

bool result = d < e;

When defining these operators, you MUST define them both ways! Ideally define them both as non-member functions

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

(Why nonmember functions? To improve encapsulation)

John Lakos has a has a wonderful CPPcon talk where he says exactly this.

AndyG
  • 39,700
  • 8
  • 109
  • 143