cpp / intermediate
Snippet
Transforming Array Elements In-Place
Using std::transform allows for concise modification of array-like containers by applying a function or lambda to each element in a specified range.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>#include <vector>#include <algorithm>int main() {std::vector<int> numbers = {1, 2, 3, 4, 5};// Apply a square function to each element using std::transformstd::transform(numbers.begin(), numbers.end(), numbers.begin(), [](int n) {return n * n;});for (int n : numbers) std::cout << n << " ";return 0;}
Breakdown
1
std::transform(numbers.begin(), numbers.end(), numbers.begin(), ...
Reads from the start to the end of the vector and writes the result back into the same starting position.
2
[](int n) { return n * n; }
A lambda function that defines the logic for the transformation (squaring the input).