How to create 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 less than 3. How to create a functor that returns the number of elements between 0 and 3? I know that boost has some features for this, but is this possible in a pure STL?

+4
source share
2 answers

If you mean the use of tools for linking the functions of the standard library, then at least not in C ++ 98. In C ++ 11, you can use std::bind for an 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 it really does not give a headache for such a simple predicate.

If the capabilities of C ++ 11 are enabled, then the simplest way is likely to be lambda, there is no need to create a complex composition (on its own):

 int count = std::count_if(v.begin(), v.end(), [](int arg) { return arg > 0 && arg < 3; }); 

But for C ++ 98 Chubsdad, the answer is probably the best solution.

+8
source

Is that what you ask? I know this is not a pure STL, but still ..

 struct InRange { InRange(int x, int y) : mx(x), my(y) { } bool operator()(int x) { return (x >= mx) && (x <= my); } int mx, my; }; int main() { std::vector<int> v; v.push_back(13); v.push_back(14); v.push_back(18); v.push_back(3); int count = std::count_if(v.begin(), v.end(), InRange(0, 3)); } 
+5
source

All Articles