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:
Syntax:
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)
where,
- 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.
Syntax:
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:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int size = 5;
vector< int > V(size, 0);
srand ( time (0));
generate(V.begin(), V.end(), rand );
cout << "The elements of vector are:\n" ;
for ( int i = 0; i < size; i++) {
cout << V[i] << " " ;
}
return 0;
}
|
Output:
The elements of vector are:
995552582 698831766 2088692742 1348138651 64302615
Last Updated :
24 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...