本文介绍了将满足某种条件的所有元素从一个容器移动到另一个容器,即我正在寻找某种“ move_if”容器。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出
std::vector<T> first = /* some given data */, second;
我想移动所有元素 e
满足某些条件 cond(e)
从第一
到
,例如
I want to move all elements e
which satisfy some condition cond(e)
from first
to second
, i.e. something like
move_if(std::make_move_iterator(first.begin()),
std::make_move_iterator(first.end()),
std::back_inserter(second), [&](T const& e)
{
return cond(e);
});
我无法通过算法库来建立此链接。那么,我该怎么办呢?
I wasn't able to establish this with the algorithms library. So, how can I do that?
推荐答案
如果移出的元素可以留在首先,然后将 copy_if
与 move_iterator
一起使用。
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);
如果应该先从删除移出的元素
,我愿意
// 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());
或 partition_copy
或 move_iterator
,然后分配:
std::vector<T> 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);
这篇关于将满足某种条件的所有元素从一个容器移动到另一个容器,即我正在寻找某种“ move_if”容器。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!