Boost logo

Boost Users :

From: Witz (witz_at_[hidden])
Date: 2003-09-15 12:51:24

> > template<class II, class OI, class PRED>
> > std::pair<II,OI> copy_if(II ibegin, II iend, OI obegin, OI oend,
> > PRED p)
> > {
> > for(; ibegin != iend; ++ibegin)
> > {
> > if(p(*ibegin))
> > {
> > *obegin = *ibegin;
> > if(++obegin == oend)
> > break;
> > }
> > }
> > return std::make_pair(ibegin, obegin);
> > }
> >
> This should check whether obegin == end before copying, in case obegin
> == oend initially. I don't know whether it should stop as soon as it
> finds obegin == oend or wait until it knows there's another item to be
> copied. The former behaviour saves a little time in the case that no
> more items are wanted once the output buffer is full. The latter
> behaviour avoids the occasional need for another pass that copies
> nothing, if copy_if is called repeatedly to fill an output buffer which
> is then flushed.

> Ben.

I've tended to rely on the common sense of the user (after all i cannot
detect other possible errors such as 'oend < obegin') but i suppose the
following addition at the start would seem sensible:

ASSERT(obegin != oend);

As for your second point - the amount of time saved by 'the former
behaviour' depends on how expensive the predicate is and how many times it
will be called if no more satisfactory items are available. As the entries
in the output buffer are overwritten as and when required there is no need
in any general sense to clear it between calls and this surely obviates any
advantage your proposed approach may have.


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at