std::copy_if

With C++0x std::copy_if() is finally here, hurray! But, what if your compiler does not support yet the new standard? You have to write it yourself.

Good news is that the code is quite simple:

template<typename InputIterator, typename OutputIterator, typename Predicate>
OutputIterator my_copy_if(InputIterator begin, InputIterator end, OutputIterator to, Predicate p)
{
while(begin != end)
{
if(p(*begin))
*to++ = *begin;
++begin;
}
return to;
}

Let's see it at work, because it is a good reason to see copy_if, a back_inserter and a lambda function in the same line.

As usual, first step is about setting up the input data:

std::vector<int> vi;
vi.reserve(10);
for(int i = 0; i < 10; ++i)
vi.push_back(i);
dump(vi);

An then let's copy only the even elements:

std::vector<int> vo;
std::copy_if(vi.begin(), vi.end(), std::back_inserter(vo),
[] (int i) -> bool { return i %2 == 0; });
dump(vo);

Here I used the standard copy_if() - using our version won't change the test code.

Why copy_if() has to be written how we see it, and more info on the matter in Item 36 of Effective STL, one of the Effective C++ book series by Scott Meyers.

No comments:

Post a Comment