How can I combine some functors to generate a `isOdd` function?
How can I combine several functors to generate a开发者_开发技巧 isOdd functor?
equal_to
modulus
bind2nd
...
int nums[] = {0, 1, 2, 3, 4};
vector<int> v1(nums, nums+5), v2;
remove_copy_if(v1.begin(), v1.end(), back_inserter(v2), isOdd);
v2 => {0, 2, 4}
Using just the primitives provided in the standard libraries, this is actually surprisingly difficult because the binders provided by bind1st and bind2nd don't allow you to compose functions. In this particular case, you're trying to check if
x % 2 == 1
Which, if you consider how the <functional> primitives work, is equivalent to
equal_to(modulus(x, 2), 1)
The problem is that the components in <functional> don't allow you to pass the output of one function as the input to another function very easily. Instead, you'll have to rely on some other technique. In this case, you could cheat by using two successive applications of not1:
not1(not1(bind2nd(modulus<int>(), 2)))
This works because it's equivalent to
!!(x % 2)
If x is even, then this is !!0, which is false, and if x is odd this is !!1, which is true. The reason for the double-filtering through not1 is to ensure that the result has type bool rather than int, since
bind2nd(modulus<int>(), 2)
is a function that produces an int rather than the bool you want.
isOdd can be defined as:
bind2nd(modulus<int>(),2)
加载中,请稍侯......
精彩评论