Search code examples
c++functionbooleanoverloadingfunctor

Functor or boolean comparator


What should I use? bool compare or sCompare() functor? And why? Are there some differences between using this two options?

struct Dog
{
    int m_age{};
    int m_weigt{};
};

bool compare(const Dog& a, const Dog& b)
{
    return a.m_age > b.m_age;
}

struct sCompare
{
    bool operator()(const Dog& a, const Dog& b)
    {
        return a.m_age > b.m_age;
    }
};

int main()
{
    vector<Dog> dogs{ Dog{1,20}, Dog{2,10}, Dog{3,5}, Dog{10,40} };
    //sort(begin(dogs), end(dogs), compare); this
    //sort(begin(dogs), end(dogs), sCompare()); or this

    return 0;
}

Solution

  • Your two comparators result in opposite ordering (< vs >). Other than that the biggest difference is that you cannot define a function within a function, but you can define a type in a function. Moreover, lambda expressions offer straightforward syntax to do that:

    int main()
    {
        vector<Dog> dogs{ Dog{1,20}, Dog{2,10}, Dog{3,5}, Dog{10,40} };
        sort(begin(dogs), end(dogs), [](const Dog& a,const Dog& b){ return a.m_age < b.m_age;});
        // or 
        auto comp = [](const Dog& a,const Dog& b){ return a.m_age < b.m_age;}
        sort(begin(dogs), end(dogs),comp); 
    
    }