Example 1 — Keep the original
Change 2 to 20 in a copy and show both vectors.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> src = {1, 2, 3, 2};
std::vector<int> out(4);
std::replace_copy(src.begin(), src.end(), out.begin(), 2, 20);
std::cout << "src: ";
for (int x : src) std::cout << x << ' ';
std::cout << '\n';
std::cout << "out: ";
for (int x : out) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
src: 1 2 3 2
out: 1 20 3 20
How It Works
out is created with four slots to receive the copy.- Each value is copied, but 2 is replaced by 20 on the way.
- The printed
src is unchanged, which is the main point.
Example 2 — Replace words
Swap one word for another in a new vector.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words = {"red", "blue", "red"};
std::vector<std::string> out;
std::replace_copy(words.begin(), words.end(), std::back_inserter(out),
std::string("red"), std::string("green"));
for (const std::string& x : out) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
How It Works
- Both values are
std::string, so they have the same type. std::back_inserter grows out for each copied word.- Only the
red entries are replaced.
Example 3 — Change characters
Turn dashes into spaces in a new string.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main() {
std::string text = "a-b-c";
std::string result;
std::replace_copy(text.begin(), text.end(), std::back_inserter(result), '-', ' ');
std::cout << result << '\n';
std::cout << text << '\n';
return 0;
}
How It Works
result starts empty and grows with std::back_inserter.- Each
'-' is written as a space in the new string. - The original
text is printed last and still has its dashes.