Given two vectors of copyable elements and a predicate over those items, what is an efficient and idiomatic method for:
- Removing matching items from the first vector
- Appending matching items to the second vector
The following snippet reflects my current thinking, but it does require two passes over the source vector.
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());