How to generate a vector with random values in C++?
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:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v(10);
// Create a random number generator between 0 to 100
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(0, 100);
// Initialize vector elements with random values
for (int i = 0; i < 10; ++i)
v[i] = dis(gen);
for (auto i : v)
cout << i << " ";
return 0;
}
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.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v(10);
// Generate 10 random numbers between 0 and 100
for (int i = 0; i < 10; ++i)
v[i] = rand() % 100;
for (auto i : v)
cout << i << " ";
return 0;
}
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.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v(10);
// Populate the vector with random values
generate(v.begin(), v.end(), []() {
return rand() % 100;
});
for (auto i : v)
cout << i << " ";
return 0;
}
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.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v;
// Fill vector with 10 random values
fill_n(back_inserter(v), 10, rand() % 100);
for (auto i : v)
cout << i << " ";
return 0;
}
Output
83 83 83 83 83 83 83 83 83 83