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::views::zip

Use case

Iterate multiple ranges together.

Explanation

std::views::zip combines multiple ranges into tuples. Iterates in “lockstep”. Stops at shortest range.

Code

#include <cstdint>
#include <print>
#include <ranges>
#include <string>
#include <vector>

int main() {
  std::vector<uint64_t> addresses = {0x1000, 0x1100, 0x1200};
  std::vector<std::string> names = {"_main", "_helper", "_exit"};
  std::vector<size_t> sizes = {0x100, 0x50, 0x50};

  for (auto [addr, name, size] : std::views::zip(addresses, names, sizes)) {
    std::println("{:#x}: {} (size: {:#x})", addr, name, size);
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++23/build/std-views-zip
0x1000: _main (size: 0x100)
0x1100: _helper (size: 0x50)
0x1200: _exit (size: 0x50)