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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?