How to generate a vector with random values in C++?
Vectors are dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. It can also be created with random value using the generate function and rand() function.
Below is the template of both the STL functions:
int rand(void): It returns a pseudo-random number in the range of 0 to RAND_MAX.
RAND_MAX: is a constant whose default value that may vary between implementations but it is granted to be at least 32767.
void generate(ForwardIterator first, ForwardIterator last, Generator gen)
- first: Forward iterator pointing to the first element of the container.
- last: Forward iterator pointing to the last element of the container.
- gen: A generator function, based upon which values will be assigned.
- Returns Value: Since, it has a void return type, so it does not return any value.
In order to have different random vectors each time, run this program, the idea is to use srand() function. Otherwise, the output vector will be the same after each compilation.
void srand(unsigned seed): This function seeds the pseudo-random number generator used by rand() with the value seed.
Below is the implementation of the above approach:
The elements of vector are: 995552582 698831766 2088692742 1348138651 64302615