VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-generate-a-vector-with-random-values-in-c/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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:


Output
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:


Using rand() Function

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.


Output
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.

Using generate() with Random Function

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.


Output
83 86 77 15 93 35 86 92 49 21 

Using fill_n() with Random Values

The fill_n() function can also be used in combination with a random number generator in a similar way as generate() function.


Output
83 83 83 83 83 83 83 83 83 83 
Comment
Article Tags: