I’ve got the following code and am getting the error:
“error C2676: binary ‘>’ : ‘const Car’ does not define this operator or a conversion to a type acceptable to the predefined operator”
It’s popping up on the: if (vec[i] > returnValue) /…/ line
I get that it might be confused about how to compare the Car struct but shouldn’t that last callback/overload function take care of that? Suggestions?
#include <vector>
#include <iostream>
#include <string>
struct Car {
std::string name;
int weight;
int airbags;
};
//callback for typical compairsons
template <typename Type>
int CmpCallBack(Type one, Type two) {
if (one < two) return -1;
if (one == two) return 0;
if (one > two) return 1;
}
//itterate through vec<Type> and return max value
template <typename Type>
Type FindMax(std::vector<Type> const &vec, int (cmpFn)(Type one, Type two) = CmpCallBack) {
Type returnValue = new Type; //is this the right way to initialize this var?
for (int i = 0; i < vec.size(); i++) {
if (vec[i] > returnValue) {
returnValue = vec[i];
}
}
return returnValue;
}
//callback for the custom "Car" struct
int CarAirComp(Car one, Car two) {
if (one.airbags < two.airbags) return -1;
if (one.airbags == two.airbags) return 0;
if (one.airbags > two.airbags) return 1;
}
int main () {
//build a vector of Car types
std::vector<Car> cars;
Car x;
x.airbags = 5;
x.name = "car one";
Car y;
y.airbags = 3;
y.name = "car two";
Car z;
z.airbags = 1;
z.name = "car three";
cars.push_back(x);
cars.push_back(y);
cars.push_back(z);
//test function
Car returnVal = FindMax(cars, CarAirComp);
std::cout << "value: " << returnVal.name << std::endl;
system("pause");
return 0;
}
You do not have
operator >defined forCar. The compiler does not know how to evaluate(vec[i] > returnValue). If you define this operator, you should be fine:Additionally, you will need to change this:
to
Update:
Since you have a compare function available, you do not need to write an
operator >. Instead, use your compare function: