C ++ [Error] there are no matches for 'operator ==' (operand types are "Vehicle" and "const Vehicle")

I am working on a project for my school (I'm still a beginner) and I came across the following problem:

"[Error] no match for 'operator==' (operand types are 'Vehicle' and 'const Vehicle')" 

Vehicle is a class in my project.

This is what gives me the error:

 int DayLog::findWaitingPosistion(Vehicle const& v){ if (find(waitingList.begin(),waitingList.end(),v) != waitingList.end()) return 1; } 

waitingList - a vector of Vehicle objects.

I searched and could not find the answer, although I had many similar questions. I tried everything but nothing worked. Thanks in advance.

+6
source share
2 answers

The minimum requirements for using find is the operator== function. This is what std::find uses, since iterates through a vector if it found your type.

Something like this will be needed:

 class Vehicle { public: int number; // We need the operator== to compare 2 Vehicle types. bool operator==(const Vehicle &rhs) const { return rhs.number == number; } }; 

This will allow you to use find. The following is an example.

+2
source

The error message is pretty clear: the compiler is looking for an operator == function that compares two machines. The signature of such a method, if it existed, would be something like

 bool operator==(const Vehicle& first, const Vehicle& second); 

What is not so clear why this is happening. After all, you are not using the == operator anywhere in your code! Crummy compiler - complaining about something you didn't even do.

To understand what is going on, you must understand the “find” method. This is a boilerplate method, and in C ++, templates are quite diverse find-and-replace text (warning: massive simplification!). The code for the "search" will be generated on the fly for the types that you use immediately before starting the compiler.

You can check how the search is done here . In the unlikely event that cplusplus.com ever goes offline, I have included the relevant part below *:

 template<class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val) { while (first!=last) { if (*first==val) return first; //<--- Notice the == operator ++first; } return last; } 

Where it comes from ==; The compiler will automatically generate a search code for your type (vehicle). Then, when it goes to compilation, this generated code tries to use the == operator, but not for the vehicle. You will need to provide you with your car.

* Seriously though - check out this site . He shows you how it all works.

+4
source

All Articles