Consider the following scenario:
bool is_odd(int i)
{
return (i % 2) != 0;
}
int main()
{
// ignore the method of vector initialization below.
// assume C++11 is not to be used.
std::vector<int> v1 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> v2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// removes all odd numbers, OK
v1.erase( std::remove_if(v1.begin(), v1.end(), is_odd), v1.end() );
// remove all even numbers
v2.erase( std::remove_if(v2.begin(), v2.end(), ???), v2.end() );
}
Can I use the same is_odd()
UnaryPredicate to remove even numbers as expected in the last line of main()
. Or will I have to necessarily write a is_even()
even though it will be nothing but:
bool is_even(int i)
{
return !is_odd(i);
}
[](int i){ return !is_odd(i);}
, and I would claim clearer than something likenot1
. – Ring=
the above code requires C++11! There is no direct way to initialize astd::vector
(or any of the other standard library containers) with a sequence of elements in C++ prior to C++11. The way to do it would be creation of an array and then using iterators to the array with the construct of the container. – PunC++03
tag. The current standard is C++14; when I see just C++, I assume a reasonably recent compiler. (Even though that is not the case at work, but such is life). – Ring