On this page
std::transform
Prev: std::find_if | Up: algorithm_and_ranges | Next: std::ranges & std::views
Rel: std::ranges & std::views, std::vector
Ref: cppreference — std::ranges::transform
Tags: #public #prog #cpp #stdlib #algorithms #tier/standard
Overview
std::transform / std::ranges::transform (<algorithm>) eagerly applies a function to every element of one (or two) input ranges and writes the results to an output iterator.
Notes & Pitfalls
- Destination must have enough space: Pre-size
out(in.size())or passstd::back_inserter(out)—writing past.end()is UB. - Also supports binary transforms:
std::transform(a.begin(), a.end(), b.begin(), out.begin(), fn).
Example
#include <algorithm>
#include <cassert>
#include <iterator>
#include <vector>
int main() {
std::vector<int> in{1, 2, 3}, out;
out.reserve(in.size());
std::transform(in.begin(), in.end(), std::back_inserter(out), [](int x) { return x * 10; });
assert((out == std::vector<int>{10, 20, 30}));
}
Linked from
Related notes
- tuts/cpp/stdlib/algorithm_and_ranges/find_if Linked here; links to this page; shared tags: #algorithms, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges Linked here; links to this page; shared tags: #algorithms, #cpp, #prog, #stdlib
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views Linked here; links to this page; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/vector Linked here; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/sort shared tags: #algorithms, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/atomic shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/jthread shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/thread shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/array shared tags: #cpp, #prog, #stdlib, #tier