| CARVIEW |
Select Language
HTTP/2 200
date: Tue, 30 Dec 2025 13:46:34 GMT
content-type: text/html; charset=utf-8
server: cloudflare
last-modified: Mon, 05 Jul 2021 23:22:32 GMT
vary: Accept-Encoding
access-control-allow-origin: *
nel: {"report_to":"cf-nel","success_fraction":0.0,"max_age":604800}
expires: Tue, 30 Dec 2025 13:56:34 GMT
cache-control: max-age=600
report-to: {"group":"cf-nel","max_age":604800,"endpoints":[{"url":"https://a.nel.cloudflare.com/report/v4?s=2OkvTqJ1yOJ9w7pupstbPfp5hmlwbJlqtSAAxFQK4Sv7GxfPMXgRm6EJuR0omoAeHBqLLSA4lyxIINzmvt41x54ZYuYGyJEKzWW%2Fwic%3D"}]}
x-proxy-cache: MISS
x-github-request-id: 2749:17CAD7:6438672:6BAD20A:6953D7BA
cf-cache-status: DYNAMIC
content-encoding: gzip
cf-ray: 9b61fbebfe3459a9-BOM
alt-svc: h3=":443"; ma=86400
Choose a random element - C++ Patterns
← 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.