c – 将满足某些条件的所有元素从一个容器移动到另一个容器,即我正在寻找某种“move_if”
作者:互联网
特定
std::vector<T> first = /* some given data */, second;
我想将满足某些条件cond(e)的所有元素e从第一个移动到第二个,即类似的东西
move_if(std::make_move_iterator(first.begin()),
std::make_move_iterator(first.end()),
std::back_inserter(second), [&](T const& e)
{
return cond(e);
});
我无法用算法库建立这个.那么,我该怎么做呢?
解决方法:
如果移动的元素可以保留在它们所在的位置,那么只需将copy_if与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());
或者使用move_iterator进行partition_copy,然后进行赋值:
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);
标签:c,c11,c14 来源: https://codeday.me/bug/20191007/1868653.html