How do I avoid copies using std::transform with back_inserter in C++?

In C++, when using std::transform with std::back_inserter, you may end up making unnecessary copies of objects. To avoid this issue, you can use references (specifically & for lvalue references or std::move for rvalue references) to work directly with the original elements. Below is an example showcasing how to correctly use std::transform to avoid copies.

#include <algorithm> #include <iostream> #include <vector> #include <iterator> int main() { std::vector<int> input = {1, 2, 3, 4, 5}; std::vector<int> output; // Using std::transform to populate output without copies std::transform(input.begin(), input.end(), std::back_inserter(output), [](int& n) { return n * 2; }); // using reference for (const auto& elem : output) { std::cout << elem << " "; // Prints: 2 4 6 8 10 } return 0; }

std::transform std::back_inserter C++ avoid copies C++ performance