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.
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With