jeudi 1 janvier 2015

What's a good implementation of applying a unary function to some elements of a vector?

I'd like to apply a function UnaryFunction f to some elements of a std container, given a predicate UnaryPredicate p - sort of what you would get if you combine std::partition and then apply std::for_each to one of the partitions.


I'm quite new to C++, so forgive my ignorance. I have, however, looked for a suitable implementation in <algorithm>, yet I can't seem to find the desired function.


Based on the possible implementations over at cppreference.com, I've come up with the following:



template<class InputIt, class UnaryPredicate, class UnaryFunction>
UnaryFunction for_if(InputIt first, InputIt last, UnaryPredicate p, UnaryFunction f)
{
for (; first != last; ++first) {
if (p(*first))
{
f(*first);
}
}
return f;
}


The return value is modeled as per std::for_each, although an OutputIter might have been a better choice. This would require a more convoluted implementation though, and so I've chosen brevity over finesse this time around. The alternative implementation is left as an exercise to the reader.


My question is: is there already an established way to do this in the std library? If not, would this be a reasonable implementation of such a function template?


Aucun commentaire:

Enregistrer un commentaire