The method we've discussed so far, for structuring code in a functional way, involves passing multiple times through a collection that is treated as immutable. As a result, this can lead to copies of the collection. Let's look, for example, at a simple code sample that uses transform to increment all the elements of a vector:
template<typename DestinationType>
auto transformAll = [](const auto source, auto lambda){
DestinationType result;
transform(source.begin(), source.end(), back_inserter(result),
lambda);
return result;
};
TEST_CASE("Memory"){
vector<long long> manyNumbers(size);
fill_n(manyNumbers.begin(), size, 1000L);
auto result = transformAll<vector<long long>>(manyNumbers,
increment);
CHECK_EQ(result[0], 1001);
}
This implementation leads to a lot of memory allocations...