【发布时间】:2021-04-28 23:03:51
【问题描述】:
给定两个可复制元素的向量和对这些项目的谓词,什么是有效且惯用的方法:
- 从第一个向量中删除匹配项
- 将匹配项附加到第二个向量
下面的 sn-p 反映了我目前的想法,但它确实需要对源向量进行两次传递。
vector<int> source{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
vector<int> target;
auto predicate = [](int n) { return n % 2 == 0; };
std::for_each(source.begin(), source.end(), [&predicate, &target](int n) {
if (predicate(n)) {
target.push_back(n);
}
});
auto it = std::remove_if(source.begin(), source.end(), predicate);
source.erase(it, source.end());
【问题讨论】:
标签: c++ algorithm vector stl std