I frequently encounter situations, especially with sorting in C++, where I am comparing a series of fields in order to compare a larger structure. A simplified example:
struct Car{
Manufacturer make;
ModelName model;
Year year;
};
bool carLessThanComparator( const Car & car1, const Car & car2 ){
if( car1.make < car2.make ){
return true;
}else if( car1.make == car2.make ){
if( car1.model < car2.model ){
return true;
}else if( car1.model == car2.model ){
if( car1.year < car2.year ){
return true;
}
}
}
return false;
}
My instinctive approach seems cumbersome, especially for more than 3 fields. How would you structure this series of comparisons in C++? Do other languages provide a more succinct or elegant syntax?
strcmp()
like function (or method) that returns 0 if a equals b, 1 if a is greater than b, and -1 if a is less than b, and then define the comparison operators (if you like) and/or methods in terms of the comparison function. Then we'd just havebool carLessThanComparator( const Car & car1, const Car & car2 ) { return cmp(car1, car2) == -1; }
– Interlope