如何在C++中将匹配谓词的元素从一个向量转移到另一个向量?
给定两个可复制元素的向量和对这些项目的谓词,什么是有效且惯用的方法:
- 从第一个向量中删除匹配项
- 将匹配项附加到第二个向量
以下代码段反映了我目前的想法,但它确实需要两次遍历源向量。
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());
回答
我会使用std::partition到的分区source分成两个部分。
auto itr = std::partition(source.begin(), source.end(), predicate);
target.insert(target.end(), itr, source.end());
source.resize(itr - source.begin());
如果排序需要保持不变,则使用stable_partition.
- @OP: Notice that if you only work with iterators, you might no longer need extra vector and just use the partitioned vector.