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

Use case

Simplified algorithm calls. Pass container directly, use projections instead of lambdas.

Explanation

std::ranges:: alrogithms take containers directly (no .begin()/.end()). Projections (&Symbol::addr) extract the field to compare (replacing simple lambdas).

Code

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

struct Symbol {
  uint64_t addr;
  const char *name;
};

int main() {
  std::vector<Symbol> symbols{
      {0x1030, "_helper"}, {0x1000, "_main"}, {0x1020, "_init"}};

  std::ranges::sort(symbols, std::less{}, &Symbol::addr);

  for (const auto &s : symbols) {
    std::cout << s.name << " @ 0x" << std::hex << s.addr << "\n";
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/std-ranges
_main @ 0x1000
_init @ 0x1020
_helper @ 0x1030