Transforming Ranges (transform, copy, remove) in C++
Modifying algorithms rewrite ranges declaratively: transform applies a function element-wise into an output, copy_if filters, fill/generate populate, and remove compacts (paired with erase — the erase-remove idiom — since algorithms can't resize containers). Reverse and rotate reorder in place.
The output-iterator model keeps them container-agnostic: write into another vector, an inserter, or an output stream. Thinking in transforms replaces most hand-rolled mutation loops with named, reviewable operations.
transform maps element-wise
std::transform(in..., out..., [](int x){ return x * x; }); squares a range into output — the functional workhorse.
Erase-remove deletes
v.erase(std::remove(v.begin(), v.end(), x), v.end()); — remove compacts survivors forward, erase trims the tail. Neither works alone.
copy_if filters
std::copy_if with a predicate plus back_inserter builds filtered vectors without a single explicit loop.
reverse and rotate reorder
In-place reversal and rotation handle undo buffers, next-permutation prep, and ring shifts declaratively.
#include <iostream>#include <vector>#include <algorithm> int main() { std::vector<int> v{1, 2, 3, 4}; std::vector<int> sq; std::transform(v.begin(), v.end(), std::back_inserter(sq), [](int x) { return x * x; }); v.erase(std::remove(v.begin(), v.end(), 2), v.end()); std::cout << sq[2] << ", " << v.size() << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.