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::generate

Use case

Fill range with values produced by a generator function.

Explanation

Calls generator for each element (generator takes no arguments). Usful for creating instruction sequences.

Time complexity: O(n). Calls generator once per element. See possible implementation.

Code

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

int main() {
  std::vector<uint32_t> nopSled(5);

  std::generate(nopSled.begin(), nopSled.end(), []() {
    // $ echo "nop" | llvm-mc -triple=aarch64 -show-encoding
    // nop                                     // encoding: [0x1f,0x20,0x03,0xd5]
    return 0xd503201f;
  });

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

  return 0;
}

View on GitHub.

Output

$ ./src/algorithms/build/std-generate
0xd503201f
0xd503201f
0xd503201f
0xd503201f
0xd503201f