In this article we will discuss how to fill a std::vector with random numbers using std::generate.

For this task we will use a STL algorithm std::generate i.e.

It will update all the elements from range start to end -1 with values generated by gen function object. Suppose size of vector is n then std::generate will call the gen() n number of times and copy each value to vector from start to end -1 i.e (start, end].

But import point is std::generate() copies the elements i.e. it does not push elements. So, it expects that vector is already has the capacity i.e. vector’s size is already n.

Fill random Numbers in std::vector using Lambda functions

Let’s fill a std::vector of size 10 with random numbers from 0 to 100. First of all, initialize a vector with 10 ints of value 0 i.e.

Now fill vector by generating 10 random numbers using lambda function,

Here, std::generate iterates the vector from begin to end. During each iteration calls the lambda function and assigns each returned value to corresponding entry in vector.

Fill Random Numbers in std::vector using a Functor

Define a Functor that will return a random numbe whenever called i.e.

Now fill vector by generating 10 random numbers using above functor i.e,

Here, std::generate iterates the vector from begin to end. During each iteration calls the RandomGenerator functor and assigns each returned value to corresponding entry in vector.

 

Complete example is as follows,

To compile the above code use following command

g++ –std=c++11 sample.cpp

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.