Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::transform

Use case

Apply a function to each element and store results.

Explanation

Can transform in-place or to different container.

Time complexity: O(n). Applies transformation exactly once per element. See possible implementation.

Code

#include <algorithm>
#include <cstdint>
#include <print>
#include <vector>

int main() {
  std::vector<uint32_t> offsets = {0x10, 0x20, 0x30, 0x40};
  std::vector<uint64_t> addresses(offsets.size());

  uint64_t base = 0x10000000;

  std::transform(offsets.begin(), offsets.end(), addresses.begin(),
                 [base](uint32_t offs) { return base + offs; });

  for (const auto &addr : addresses) {
    std::println("{:#x}", addr);
  }

  return 0;
}

View on GitHub.

Output

$ ./src/algorithms/build/std-transform
0x10000010
0x10000020
0x10000030
0x10000040