Search code examples
c++coding-stylelanguage-featureslexicographicstdtuple

How do you structure your comparison functions?


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?


Solution

  • Well, if your function hits a return in the if clause, there's no need for an explicit else, since it would have already bailed out. That can save on the "indent valley":

    bool carLessThanComparator( const Car & car1, const Car & car2 ) {
        if( car1.make < car2.make )
            return true;
    
        if ( car1.make != car2.make )
            return false;
    
        if( car1.model < car2.model )
            return true;
    
        if( car1.model != car2.model )
            return false;
    
        if( car1.year < car2.year )
            return true;
    
        return false;
    }
    

    I like MarkusQ's LISPish short-circuiting approach as well.