| JezUK Ltd - C++: copy_while and copy_until |
| << Previous | January 2008 | Next >> |
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.
<
,
,
>
(
,
,
,
)
{
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]
The Forest Road Reader, No 37 (1)
The Forest Road Reader, No 19 (1)
The Forest Road Reader, No 17 (1)
The Forest Road Reader, No 10 (1)