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.

Download  Run Code

⮚ Pointer arithmetic

The following code works as we can perform pointer arithmetic on iterators.

Download  Run Code

⮚ ++ operator

Another solution is to use the ++ operator inside the while loop to advance the iterators by specified positions, as shown below:

Download  Run Code

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.

Download  Run Code

That’s all about getting a random value from STL containers in C++.