How to get a random element from a C++ container?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Getting a random element from a C++ container depends on whether the container supports random access. For std::vector and std::array, generate a random index and access directly. For std::set, std::list, and other non-random-access containers, use std::advance with an iterator or std::sample. C++17's std::sample provides a clean, generic approach that works with any container.
Random Element from std::vector (Direct Index)
This is O(1) — std::vector supports constant-time random access by index.
Why Not rand() % size?
rand() % n produces biased results when RAND_MAX + 1 is not evenly divisible by n. std::uniform_int_distribution guarantees uniform distribution.
Random Element from std::array
Same approach as std::vector — both support O(1) random access.
Random Element from std::set or std::list (No Random Access)
Containers like std::set, std::multiset, std::list, and std::map use bidirectional iterators. You cannot index into them directly, so you advance an iterator to a random position.
std::advance is O(n) for bidirectional iterators because it steps through nodes one by one.
Generic Function for Any Container
This works for any container with begin(), size(), and bidirectional iterators. It is O(1) for random-access containers and O(n) for others.
std::sample (C++17) — Select Multiple Random Elements
std::sample selects k elements without replacement using reservoir sampling. It works with forward iterators, so it handles std::set, std::list, etc.
Single Random Element with std::sample
Random Element from std::map
Random Element from std::unordered_set / std::unordered_map
These containers have forward iterators, so std::advance works but is still O(n):
If you need frequent random access from a set, consider maintaining a parallel std::vector of elements.
Common Pitfalls
- Using
rand()instead of<random>:rand()has poor randomness quality and modulo bias. Always usestd::mt19937withstd::uniform_int_distributionfor correct uniform sampling. - Empty container: Calling
dist(0, container.size() - 1)when the container is empty causes undefined behavior (underflow toSIZE_MAX). Always check!container.empty()first. - Assuming O(1) for all containers:
std::advanceis O(1) for random-access iterators (vector,array,deque) but O(n) for bidirectional (set,map,list) and forward (unordered_set) iterators. If you need frequent random selection from a non-random-access container, copy elements to a vector first. - Creating
std::random_devicein a loop:std::random_devicemay be expensive to construct and should be used once to seed the generator. Createstd::mt19937once and reuse it. - Thread safety:
std::mt19937is not thread-safe. Each thread should have its own generator instance, typically usingthread_local std::mt19937 gen(std::random_device{}());.
Summary
std::vector/std::array: Generate random index withstd::uniform_int_distribution— O(1)std::set/std::list/std::map: Usestd::advancewith a random offset — O(n)std::sample(C++17): Select one or more random elements from any container without replacement- Always use
<random>(std::mt19937+ distributions) instead ofrand()for quality and correctness - Check for empty containers before generating random indices
Related reading
- How to get an environment variable value into Dockerfile during docker build?
- how to get container host machine ip address and container name in EKS
- How to get docker-compose to always re-create containers from fresh images?
- how to get docker-compose to use the latest image from repository
- how to get DNS server in c-ares
- How to get the iterator for a successful binary_search?
- How to get filebeat to ignore certain container logs
- How to get logs of deployment from Kubernetes?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.