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::fill/std::fill_n

Use case

Fill range with a value.

Explanation

fill takes iterator range, fill_n takes a start iterator and count. Common for initializing buffers or creating NOP sleds.

Time complexity: O(n). Assigns value to each element. See possible implementation.

Code

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

int main() {
  std::vector<uint32_t> code(5);
  // $ echo "nop" | llvm-mc -triple=aarch64 -show-encoding
  // nop                                     // encoding: [0x1f,0x20,0x03,0xd5]
  constexpr uint32_t ARM64_NOP = 0xd503201f;

  std::fill(code.begin(), code.end(), ARM64_NOP);

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

  return 0;
}

View on GitHub.

Output

$ ./src/algorithms/build/std-fill
NOP sled:
0xd503201f
0xd503201f
0xd503201f
0xd503201f
0xd503201f