Open In App

How to generate a vector with random values in C++?

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to generate the vector
// with random values
#include <bits/stdc++.h>
using namespace std;
  
// Driver Code
int main()
{
    // Size of vector
    int size = 5;
  
    // Initialize the vector with
    // initial values as 0
    vector<int> V(size, 0);
  
    // use srand() for different outputs
    srand(time(0));
  
    // Generate value using generate
    // function
    generate(V.begin(), V.end(), rand);
  
    cout << "The elements of vector are:\n";
  
    // Print the values in the vector
    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
Previous
Next
Share your thoughts in the comments
Similar Reads