Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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++ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page