Learn C++
#include "stlalgorithms/alg_modify.hpp"

Transforming Ranges (transform, copy, remove) in C++

//concept

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.

//how it works
1

transform maps element-wise

std::transform(in..., out..., [](int x){ return x * x; }); squares a range into output — the functional workhorse.

2

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.

3

copy_if filters

std::copy_if with a predicate plus back_inserter builds filtered vectors without a single explicit loop.

4

reverse and rotate reorder

In-place reversal and rotation handle undo buffers, next-permutation prep, and ring shifts declaratively.

//example
#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;
}
Output
9, 3
1transform squares each element into sq via back_inserter — sq becomes 1, 4, 9, 16.
2Erase-remove deletes the 2: remove compacts to 1,3,4 plus a dead tail slot, erase drops it — size 3.
3sq[2] is 9 and v holds three survivors — both mutations verified in one line.
//use cases
Element-wise math (scaling, squaring, converting) without loops
Deleting by value with the erase-remove idiom
Filtering pipelines built from copy_if plus inserters
In-place reorder tricks (reverse, rotate) for buffers and permutations

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.