Many topics on stackoverflow have tackled this subject, but I can't manage to get it right for my example. I have a class Event with the time that the event takes place. I want to sort these objects in a vector according to that time.
I first started implementing the operator<, but then the compiler gave the following error:
Error 1 error C2582: 'operator =' function is unavailable in 'Event' c:\program files (x86)\microsoft visual studio 12.0\vc\include\algorithm 3009 1 sorting
So then I added the operator=
Below is the code I have used:
#include <algorithm> // std::sort
#include <vector> // std::vector
using namespace std;
class Event{
public:
const double time;
Event(double);
bool operator<(const Event&);
bool operator=(const Event&);
};
Event::Event(double time) :
time(time){
}
bool Event::operator<(const Event& rhs)
{
return this->time < rhs.time;
}
bool Event::operator=(const Event& rhs)
{
return this->time == rhs.time;
}
int main() {
vector<Event> vector;
Event e1 = Event(10);
Event e2 = Event(5);
Event e3 = Event(7);
vector.push_back(e1);
vector.push_back(e2);
vector.push_back(e3);
sort(vector.begin(), vector.end());
return 0;
}
When I debug, I notice that my objects aren't sorted at all. They are in the order I added them. Below is an excerpt of the 'vector' variable:
[0] {time=10.000000000000000 } Event
[1] {time=5.0000000000000000 } Event
[2] {time=7.0000000000000000 } Event
I have the following questions:
- Why aren't my events sorted in the vector when I call sort?
- Why does sort need operator= ?