Daily bit(e) of C++ | std::copy_if, std::remove_copy_if
Daily bit(e) of C++ #71, The conditional copy algorithms: std::copy_if and std::remove_copy_if
If we need selectively copy elements from one range to another, the standard offers the std::copy_if
and std::remove_copy_if
algorithms.
Both algorithms accept a predicate, copying elements for which the predicate returns true and false respectively.
#include <vector>
#include <algorithm>
#include <iterator>
std::vector<int> data{1, 2, 3, 4, 5, 6, 7, 8};
std::vector<int> dst1;
std::copy_if(data.begin(), data.end(), // all elements
std::back_inserter(dst1), // push_back elements into dst1
[](int v) { return v % 2 == 0; }); // condition
// dst1 == {2, 4, 6, 8}
std::vector<int> dst2;
std::remove_copy_if(data.begin(), data.end(), // all elements
std::back_inserter(dst2), // push_back elements into dst2
[](int v) { return v % 2 == 0; }); // negative condition
// dst2 == {1, 3, 5, 7}