Move all elements which satisfy some condition from one container to another, i.e. I'm looking for some kind of “move_if”

前端 未结 3 1121
有刺的猬
有刺的猬 2021-01-04 00:13

Given

std::vector first = /* some given data */, second;

I want to move all elements e which satisfy some co

3条回答
  •  心在旅途
    2021-01-04 00:53

    @T.C. has provided a perfectly working solution. However, at a first glance, one may not understand what the intend of that code is. So, it might be not perfect, but I tend to prefer something like this:

    template
    OutputIt move_and_erase_if(InputIt first, InputIt last, InputContainer& c, OutputIt d_first, UnaryPredicate pred)
    {
        auto dist = std::distance(first, last);
        while (first != last)
        {
            if (pred(*first))
            {
                *d_first++ = std::move(*first);
                first = c.erase(first);
                last = std::next(first, --dist);
            }
            else
            {
                ++first;
                --dist;
            }
        }
        return d_first;
    }
    

提交回复
热议问题