Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like a "default comparator"?

Tags:

c++

compare

I wrote a template that wraps a std::vector to make sure the vector is always sorted:

template <typename T> class SortedVector{
public:    
    SortedVector(bool (*comparator)(T,T)=DefaultComparator<T>){
        this->comparator = comparator;
    }
    void insertValue(T newElement){            
        vect.insert(std::lower_bound(
           vect.begin(),vect.end(),newElement,comparator),newElement);
    }
private:
    std::vector<T> vect;
    bool (*comparator)(T,T);
};

I want to be able to use a custom comparators, but in most cases it will be ok to simply use T's < operator. However, I did not find any better way than to use this

template <typename T> bool DefaultComparator(T a,T b){return a<b;}

as the default parameter.

Maybe it is a stupid question... Isn't there a nicer way to get the same without defining my own DefaultComparator?

I cannot use C++11.

like image 633
463035818_is_not_a_number Avatar asked Mar 16 '23 17:03

463035818_is_not_a_number


1 Answers

There isn't a standard function template to do what you want; but there is a standard function class template, std::less. If you were to use a generic function object, rather than restricting yourself to a function pointer, then it's easy to specify that as a default:

template <typename T, typename Comparator = std::less<T> > 
class SortedVector{
public:    
    SortedVector(Comparator comparator = Comparator()){
        this->comparator = comparator;
    }
    void insertValue(T newElement){
        // lower_bound accepts any suitable function object, so no change needed
        vect.insert(std::lower_bound(
           vect.begin(),vect.end(),newElement,comparator),newElement);
    }
private:
    std::vector<T> vect;
    Comparator comparator;
};
like image 128
Mike Seymour Avatar answered Mar 27 '23 10:03

Mike Seymour