Re: Conditionally copying text to string

From: Peter Kragh (__remove__this__peter.kragh_at_mensa.dk)
Date: 02/15/04


Date: Sun, 15 Feb 2004 19:55:22 +0100

Thomas Matthews wrote:
>
> I would like to use STL algorithms and predicates,
> but I have found anything suitable (something like
> copy_until). I have searched Josutti's book[2] and
> did not see any algorithms that would accomplish my
> objective in one pass. I could use the string::find
> method, then a copy, but that is 2 passes.

Then why not make a copy_until :-)

Wanting to use the standard algorithms is IMHO a good thing, but when they
don't fit, I see no reason for not making a new one by myself.

Try something like this:

template<typename InIt, typename OutIt, typename Pred>
OutIt copy_until(InIt first, InIt end, OutIt x, Pred pred)
{
    for(; first != end; ++first, ++x)
    {
        if(pred(*first))
        {
            return x;
        }
        *x = *first;
    }
    return x;
}

You can use it like this:

// Copy until space
copy_until(
    buffer_ptr,
    buffer_ptr + strlen(buffer_ptr),
    std::back_inserter(name_field),
    isspace);

... or

// Copy until "
copy_until(
    buffer_ptr,
    buffer_ptr + strlen(buffer_ptr),
    std::back_inserter(name_field),
    std::bind2nd(std::equal_to<char>(), '"');

HTH.

Peter