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

前端 未结 3 1144
有刺的猬
有刺的猬 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 01:00

    If the moved-from elements can stay where they are in first, then just use copy_if with move_iterator.

    std::copy_if(std::make_move_iterator(first.begin()),
                 std::make_move_iterator(first.end()),
                 std::back_inserter(second), cond);
    

    If the moved-from elements should be erased from first, I'd do

    // partition: all elements that should not be moved come before 
    // (note that the lambda negates cond) all elements that should be moved.
    // stable_partition maintains relative order in each group
    auto p = std::stable_partition(first.begin(), first.end(),
                                   [&](const auto& x) { return !cond(x); });
    // range insert with move
    second.insert(second.end(), std::make_move_iterator(p),
                                std::make_move_iterator(first.end()));
    // erase the moved-from elements.
    first.erase(p, first.end());
    

    Or partition_copy with a move_iterator, followed by assignment:

    std::vector new_first;
    std::partition_copy(std::make_move_iterator(first.begin()),
                        std::make_move_iterator(first.end()),
                        std::back_inserter(second), std::back_inserter(new_first), cond);
    first = std::move(new_first);
    

提交回复
热议问题