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

Use case

Random sampling from symbol table.

Explanation

std::sample randomly selects n elements from a range (without replacement, meaning once an element is picked, it cannot be picked again).

Code

#include <algorithm>
#include <iostream>
#include <random>
#include <vector>

int main() {
  std::vector<const char *> symbols = {"_main", "_helper", "_init", "_fini",
                                       "_start"};

  std::vector<const char *> sampled;

  std::sample(symbols.begin(), symbols.end(), std::back_inserter(sampled), 2,
              std::mt19937{std::random_device{}()});

  for (auto s : sampled) {
    std::cout << s << "\n";
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/std-sample
_init
_fini