I want to write custom comparators for functions like lower_bound
, find
, etc. Below is an example of a custom comparator implemented with a functor that takes another function object (std::less
, std::greater
, etc) and use it to compare the first element of a pair with the second argument of the function.
template <template <typename> class P = std::less>
struct custom_comp {
template <class T1, class T2>
bool operator()(const std::pair<T1, T2>& pair, const T1& val)
{
return P<T1>()(pair.first, val);
}
}
Usage example:
vector<pair<int,int>> vec = {{1, 4}, {3, 3}, {5, 6}, {8, 8}};
auto first = lower_bound(begin(vec), end(vec), 5, custom_comp<>());
However the <>()
bothers me, I feel it takes away readability. Is there a way to get rid of it? (perhaps changing the functor for another kind of structure).
btw: I don't want to use lambdas because I want to reuse these custom comparators and even extend them to take more template arguments (like custom filters, e.g a functor that takes a pair and returns pair.first
, or a functor that takes the mean of a vector, etc).
Aucun commentaire:
Enregistrer un commentaire