c++comparatorcustom-compare

Using same function for sorting a vector<X> and custom comparator in set<X>


This might sound like a stupid problem but I wondered for a long time is there a better way that this:

struct X
{
    int a;
    int b;
};
bool sortComp(const X first, const X second)
{
    if (first.a!=second.a)
        return (first.a<second.a);
    else
        return (first.b<second.b);

}
class setComp
{
public:
    bool operator() (const X first, const X second) const
    {
        if (first.a!=second.a)
                return (first.a<second.a);
            else
                return (first.b<second.b);
    }
};
int main()
{
    vector<X> v;
    set<X, setComp> s;
    sort(begin(v), end(v),sortComp);
}

As you see I implement the same functionality twice, once for sorting, and once for implicit sorting in the set. Is there a way to avoid code duplication?


Solution

  • Sure, just choose one of both and change the call of the other.

    // choosing the function object
    sort(begin(v), end(v), setComp()); // create setComp, sort will call operator()
    
    // choosing the function
    set<X, bool(*)(const X, const X)> s(sortComp); // pass function pointer
    

    I personally would recommend the functor version.