Example 1 — Skip one value
Copy a vector without any 2s.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> src = {1, 2, 3, 2, 1};
std::vector<int> out;
std::remove_copy(src.begin(), src.end(), std::back_inserter(out), 2);
std::cout << "src size: " << src.size() << '\n';
std::cout << "out: ";
for (int x : out) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
How It Works
remove_copy() reads each value and writes it only if it is not 2.std::back_inserter makes out grow with each written value.- The source still has five elements, because it was not changed.
Example 2 — Skip a letter
Build a string without the letter a.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main() {
std::string word = "banana";
std::string out;
std::remove_copy(word.begin(), word.end(), std::back_inserter(out), 'a');
std::cout << out << '\n';
return 0;
}
How It Works
- The source is
banana, a range of six characters. - Each
'a' is skipped during the copy. - Only b, n and n are written to
out.
Example 3 — Copy into an array
Use the returned pointer to count what was copied.
#include <algorithm>
#include <iostream>
int main() {
int src[] = {4, 0, 5, 0, 6};
int dst[5] = {};
int* end = std::remove_copy(src, src + 5, dst, 0);
std::cout << "Copied " << (end - dst) << ": ";
for (int* p = dst; p != end; ++p) {
std::cout << *p << ' ';
}
std::cout << '\n';
return 0;
}
How It Works
- Plain arrays and pointers work as iterators.
- The two zeros are skipped, so only three values are copied.
- The returned pointer
end marks the end of the copied data inside dst.