I need a function apply(Function f, Container &c)
which would apply a given function to a range (container).
std::vector<int> a = {1, 5, 2, 4, 3};
apply(std::sort, a); // {1, 2, 3, 4, 5}
apply(std::reverse, a); // {5, 4, 3, 2, 1}
This is a basic example of the behaviour I am looking for. Also, returning the value of the function (for example std::max_element
) and variadic arguments (lambda comparators for sorting) would be nice bonuses.
Actually I can't even pass std::sort
or std::reverse
as a function to a function. What I tried is:
template<typename F, typename T>
void apply(const F &f, T &a) {
f(a.begin(), a.end());
}
and:
template<typename T, typename U>
U apply(U (*f)(typename T::iterator, typename T::iterator), T &a) {
return (*f)(a.begin(), a.end());
}
Both are giving me apply(<unresolved overloaded function type>, std::vector<int>&)
.
So, is there a way to do it and what's the most modern way to do it?