Vector fill c++ – How to Fill a Vector with Random Numbers in C++

Vector fill c++: In the previous article, we have discussed about C++ std::vector Why should I use std::vector with example. Let us learn how to Fill a Vector with Random Numbers in C++ Program.

Filling a Vector with Random Numbers in C++

C++ vector fill: In this article, we will learn to fill std::vector with random numbers by the help of std::generate.

Syntax: template<typename _FIter, typename _Generator>
            void  generate(_FIter start, _FIter end, _Generator gen);

Here the elements will be updated from start to end-1 using gen function. If a vector has size n, then std::generate calls gen function n number of times and copies elements from start to end-1.

Let’s see one by one.

Filling random Numbers in std::vector using Lambda functions :

Fill a vector c++: Let’s try to fill std::vector of size 5 with random numbers from 0 to 30. Then by calling gen function std::generates iterates from start to end.

During iterations, lambda function is called and to each corresponding entry, returned value is assigned to the vector.

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>

int main(){ 

// Initialize a vector with 10 elements with value 0
std::vector<int> vecRandomNo(5);

//Vector is filled with 10 random numbers
// 10 random numbers generated using lambda function
std::generate(vecRandomNo.begin(), vecRandomNo.end(), []() {
    return rand() % 30;
});
    std::cout << "5 Random Numbers generated by Lambda Function are : " << std::endl;
    for (int val : vecRandomNo)
        std::cout << val << std::endl;
}
Output :
5 Random Numbers generated by Lambda Function are :
13
16
27
25
23

Filling Random Numbers in std::vector using a Functor :

C++ std fill: Let’s try to fill std::vector with 5 random numbers with functor. Then std::generate iterates from start to end of the vector.

During iterations, RandomNoGenerator functor is called and to each corresponding entry, returned value is assigned to the vector.

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
struct RandomNoGenerator {
    int maxValue;
    RandomNoGenerator(int max) :
            maxValue(max) {
    }
    int operator()() {
        return rand() % maxValue;
    }
};

int main(){
    // Initialize a vector with 10 elements of value 0
    std::vector<int> vecRandomNo(5);
    std::generate(vecRandomNo.begin(), vecRandomNo.end(), []() {
        return rand() % 100;
    });
    // Generate 5 random numbers by a Functor
    // Assign the values to the vector
    std::generate(vecRandomNo.begin(), vecRandomNo.end(),
            RandomNoGenerator(30));
    std::cout << "5 Random Numbers generated by Functor are : " << std::endl;
    for (int val : vecRandomNo)
        std::cout << val << std::endl;
    return 0;
}

Output :
5 Random Numbers generated by Functor are :
25
16
12
9
1