Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compose functors with STL?

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?

like image 249
oddin Avatar asked Dec 11 '22 19:12

oddin


1 Answers

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.

like image 51
Christian Rau Avatar answered Dec 20 '22 22:12

Christian Rau