Monday, April 18, 2011

The copy_if that's missing in STL

We have algorithm copy() in STL. For a number of other algorithms named algo(), there is usually a corresponding algo_if() available, but unfortunately not for copy(). IMO, copy_if() should have been included in STL; it could be implemented as follows.

namespace ste {

template<typename In, typename Out, typename Pred>
Out copy_if(In first, In last, Out res, Pred p)
{
    while (first != last)
    {
        if (p(*first)) *res++ = *first;
        ++first;
    }
    return res;
}

}


It can be placed in file algorithm.hpp under directory .../ext/, whose parent may be added as an entry in included directories. As such, it may then be included as

#include <ext/algorithm.hpp>

No comments:

Post a Comment