11.7. Initializing a Container with Random Numbers
Problem
You want to fill an arbitrary container with random numbers.
Solution
You can use either the generate
or
generate_n
functions from the <algorithm>
header with a functor that returns random numbers. See
Example 11-13 for an example of how to
do this.
Example 11-13. Initializing containers with random numbers
#include <algorithm> #include <vector> #include <iterator> #include <iostream> #include <cstdlib> using namespace std; struct RndIntGen { RndIntGen(int l, int h) : low(l), high(h) { } int operator()() const { return low + (rand() % ((high - low) + 1)); } private: int low; int high; }; int main() { srand(static_cast<unsigned int>(clock())); vector<int> v(5); generate(v.begin(), v.end(), RndIntGen(1, 6)); copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n")); }
The program in Example 11-13 should produce output similar to:
3 1 2 6 4
Discussion
The standard C++ library provides the functions generate
and generate_n
specifically for
filling containers with the result of a generator function. These functions accept a
nullary functor (a function pointer or function object with no arguments) whose result is
assigned to contiguous values in the container. Sample implementations of the generate
and generate_n
functions are shown in Example
11-14.
Example 11-14. Sample implementations of generate and generate_n
template<class Iter_T, class Fxn_T> void generate(Iter_T first, Iter_T last, Fxn_T f) { while (first != last) *first++ ...
Get C++ Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.