I have code to remove all elements from std::vector<int>
that are less than some int limit
. I wrote some functions that partially use lambdas:
auto less_than_limit = [](int limit) { return [=](int elem) { return limit > elem; }; }; auto less_than_three = less_than_limit(3);
When I test it with std::vector<int> v{1,2,3,4,5};
I get the expected results:
for(auto e: v) { std::cout << less_than_three(e) << " "; }
I can easily remove all elements of less than three:
auto remove_less_than_three = std::remove_if(std::begin(v), std::end(v), less_than_three); v.erase(remove_less_than_three, v.end()); for(auto e: v) { std::cout << e << " "; }
How to remove items that are greater than or equal to 3 using less_than_three
?
I tried wrapping less_than_three
in std::not1
, but got errors:
/usr/local/Cellar/gcc/5.3.0/include/c++/5.3.0/bits/stl_function.h:742:11: error: no type named 'argument_type' in 'struct main()::<lambda(int)>::<lambda(int)>' class unary_negate ^ /usr/local/Cellar/gcc/5.3.0/include/c++/5.3.0/bits/stl_function.h:755:7: error: no type named 'argument_type' in 'struct main()::<lambda(int)>::<lambda(int)>' operator()(const typename _Predicate::argument_type& __x) const /usr/local/Cellar/gcc/5.3.0/include/c++/5.3.0/bits/predefined_ops.h:234:30: error: no match for call to '(std::unary_negate<main()::<lambda(int)>::<lambda(int)> >) (int&)' { return bool(_M_pred(*__it)); } ^
Then I tried std::not1(std::ref(less_than_three))
, but got the following errors:
/usr/local/Cellar/gcc/5.3.0/include/c++/5.3.0/bits/stl_function.h:742:11: error: no type named 'argument_type' in 'class std::reference_wrapper<main()::<lambda(int)>::<lambda(int)> >' class unary_negate ^ /usr/local/Cellar/gcc/5.3.0/include/c++/5.3.0/bits/stl_function.h:755:7: error: no type named 'argument_type' in 'class std::reference_wrapper<main()::<lambda(int)>::<lambda(int)> >' operator()(const typename _Predicate::argument_type& __x) const ^ /usr/local/Cellar/gcc/5.3.0/include/c++/5.3.0/bits/predefined_ops.h:234:30: error: no match for call to '(std::unary_negate<std::reference_wrapper<main()::<lambda(int)>::<lambda(int)> > >) (int&)' { return bool(_M_pred(*__it)); } ^
How can I negate a function in std::remove_if
without changing the logic of my lambdas? In other words, how can I emulate remove_unless
?