← Patterns

Choose a random element

12345678910111213#include <random> #include <vector> int main() { std::vector<int> v = {10, 15, 20, 25, 30}; std::random_device random_device; std::mt19937 engine{random_device()}; std::uniform_int_distribution<int> dist(0, v.size() - 1); int random_element = v[dist(engine)]; }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Choose a random element from a container.

Description

On line 6, we create a std::vector from which we want to select a random element.

We then effectively roll a die where the numbers on the die are the indices of elements in the container. That is, we seed the std::mt19937 on lines 8–9 and create a uniform random distribution of integers from 0 to v.size() - 1 inclusive on line 10. This distribution will give us any integer in this range with equal probability.

On line 12, we call dist(engine) to generate the random index, and use this value to access an element from v.

Contributors

  • Joseph Mansfield

Last Updated

27 August 2018

Source

Fork this pattern on GitHub

Share