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

Use case

Composable, lazy sequence operations.

Explanation

Views are lazy, no copies until we iterate. Pipe | chains operations. Common views: filter, transform, take, drop, reverse, split, join.

Code

#include <cstdint>
#include <iostream>
#include <ranges>
#include <vector>

int main() {
  std::vector<uint64_t> addresses{0x1000, 0x1010, 0x2000, 0x1020, 0x3000};

  auto view = addresses |
              std::views::filter([](auto a) { return a < 0x2000; }) |
              std::views::transform([](auto a) { return a - 0x1000; });

  for (auto addr : view) {
    std::cout << "0x" << std::hex << addr << "\n";
  }
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/std-views
0x0
0x10
0x20