<< PreviousJanuary 2008Next >>

Thursday 03 January, 2008
#C++: copy_while and copy_until

template<typename InIter, typename OutIter, typename Pred>
OutIter copy_while(InIter first, InIter last, OutIter dest, Pred pred)
{
  for(; first != last && pred(*first); ++first, ++dest)
    *dest = *first;
  return dest;
} // copy_while

template<typename InIter, typename OutIter, typename Pred>
OutIter copy_until(InIter first, InIter last, OutIter dest, Pred pred)
{
  return copy_while(first, last, dest, std::not1(pred));
} // copy_until

For a warm smug feeling, briefly outline possible problems with the above code.

allan@allankelly.net said Interesting, on bloglines I don't see any of the a-z characters, all I get is:

<

,

,

>

(

,

,

,

)

{

etc.

So I see quite a few problems... [added 4th Jan 2008]

I don't think it liked my markup. I've changed, it but it hasn't noticed yet. Let's see what happens :) [added 4th Jan 2008]

The slightly tedious answer, by the way, is the the use of std::not1 in copy_until requires pred be an adaptable predicate (by, for example, having Pred derive from std::unary_function). This means using a simple free function as your predicate, which people expect to be able to do, isn't possible. I guess you could dink around creating traits classes and partial specialisations and so on, but it's easier just to rewrite as:

template<typename InIter, typename OutIter, typename Pred>
OutIter copy_until(InIter first, InIter last, OutIter dest, Pred pred)
{
  for(; first != last && !pred(*first); ++first, ++dest)
    *dest = *first;
  return dest;
} // copy_until

And no, Allan, this isn't an argument to program in some other language.

[added 4th Jan 2008]

[Add a comment]