![]() |
VOOZH | about |
Generating a vector with random values means creating a vector of n elements and initialize each element some random values. In this article, we will learn different methods to initialize a vector with random values in C++.
The recommended method to initialize a vector with random values is by using a random number generator from C++'s <random> library. Let's take a look at an example:
61 63 100 12 21 24 52 61 51 38
Explanation: The <random> library allows you to generate numbers in a specific range using distribution objects like uniform_int_distribution.
C++ also provides some other methods to generate a vector with random values. Some of them are as follows:
The rand() function generates pseudo-random numbers which can be used to populate a vector by calling rand() for each element and storing the results.
83 86 77 15 93 35 86 92 49 21
Explanation: The rand() function generates pseudo-random integers. The modulo operator (%) is used to limit the range of random values.
The generate() function from <algorithm> allows you to populate a vector with given values. You can use the random number generator to provide the random values for generate() function.
83 86 77 15 93 35 86 92 49 21
The fill_n() function can also be used in combination with a random number generator in a similar way as generate() function.
83 83 83 83 83 83 83 83 83 83