Get a random value from STL containers (vector, list, set) in C++
This post will discuss how to get a random value from STL containers in C++ like std::vector, std::list, std::set, std::map, etc.
1. Using iterators
We can use the iterators to get a random value in a given STL container. We know that all STL containers support the iterators. The idea is to generate a random number r between 0 and n-1, where n is the container’s size. Then we take an iterator to the beginning of the given container and advance that iterator by r positions. Now the object pointed by the iterator will be our random value.
To generate the random values between 0 and n-1, we can use the cstdlib’s functions rand() and srand() or use any of the standard generators defined in the <random> header introduced in C++11.
There are many alternatives to advance the iterator by r positions:
⮚ Using std::advance
The standard algorithm std::advance can be used to advance the iterator by specified positions.
|
1 2 3 4 5 6 7 8 9 |
template<typename T> T random(std::vector<T> const &v) { auto it = v.cbegin(); int random = rand() % v.size(); std::advance(it, random); return *it; } |
⮚ Pointer arithmetic
The following code works as we can perform pointer arithmetic on iterators.
|
1 2 3 4 5 6 7 8 |
template<typename T> T random(std::vector<T> const &v) { auto it = v.cbegin(); int random = rand() % v.size(); return *(it + random); } |
⮚ ++ operator
Another solution is to use the ++ operator inside the while loop to advance the iterators by specified positions, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
template<typename T> T random(std::vector<T> const &v) { auto it = v.cbegin(); int random = rand() % v.size(); while (random--) { ++it; } return *it; } |
2. Using [] operator
We can also use the member function operator[] provided by the sequence containers like std::vector, std::array, std::deque which use contiguous storage locations for their elements. This approach works as the [] operator returns the element at the specified position in the container.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <vector> #include <algorithm> template<typename T> T random(std::vector<T> const &v) { int r = rand() % v.size(); return v[r]; } int main() { std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int i = 0; i < 5; i++) { std::cout << random(v) << std::endl; } return 0; } |
That’s all about getting a random value from STL containers in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)