Algorithms with output require allocated data

Algorithms that write data to an output iterator, such as std::copy() or std::transform(), requires already allocated data reserved for the output. As the algorithms only use iterators as arguments, they cannot allocate data by themselves. To enlarge the container the algorithms operate on, they rely on the iterator to be capable of enlarging the container it iterates.

If an iterator to an empty container is passed to the algorithms for output, the program will crash. The following example, where squared is empty, illustrates the problem:

auto vals=std::vector<int>{  1, 2, 3, 4};auto squared=std::vector<int>{};std::transform(  vals.begin(),   vals.end(),  squared.begin(),  [](int v) { return v ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.