Home > OS >  Understanding custom comparators in C
Understanding custom comparators in C

Time:09-30

static bool cmp(string &a,string &b)
{
    if(a.size()==b.size())
    {
        return a<b;
    }
    return a.size()<b.size();
}

This is a custom comparator to compare two strings that consist of big numbers, like "3922" and "12929", and compare them to see which is larger. However, I don't understand why when a.size() == b.size() we return a < b?

CodePudding user response:

if statement will execute only if the size of both strings is the same.(i.e "232" is equal to "934". but it will not execute for string-like ("2342", "234242").

and in the if statement you are comparing strings, not integers. so if want to compare integers then covert them first.

CodePudding user response:

Common algorithms in the standard library like std::lower_bound and std::sort make use of just one comparison function assumed to provide the result of a < b, which is enough to make all the other comparisons (if they need to test equality they can do !(a < b || b < a), for instance).

If this custom function didn't check the length of the strings, "1000" would come before "50" in lexicographical order, which is what std::string's operator<(...) uses (and what is used in that function when their length is equal).

  • Related