The following is possible in STL:
int count = count_if(v.begin(), v.end(), bind2nd(less<int>(), 3));
This returns the number of elements in v that are smaller than 3. How do compose a functor that returns the number of elements between 0 and 3? I know boost has some facilities for this but is it possible in pure STL?
If you mean by using the functor composition facilities of the standard library, then no, at least not in C++98. In C++11 you could use std::bind
for arbitrary composition of functors:
using std::placeholders;
int count = std::count_if(v.begin(), v.end(),
std::bind(std::logical_and<bool>(),
std::bind(std::less<int>(), _1, 3),
std::bind(std::greater<int>(), _1, 0)));
But that doesn't really pay the headache for such a simple predicate.
If C++11 features are allowed, then the simplest way would probably be a lambda, no need to make a complex functor composition (yourself):
int count = std::count_if(v.begin(), v.end(), [](int arg) {
return arg > 0 && arg < 3; });
But for C++98 Chubsdad's answer is probably the best solution.
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