Initializing a Container with Random Numbers - C++ STL Algorithm

C++ examples for STL Algorithm:generate

Description

Initializing a Container with Random Numbers

Demo Code

#include <ctime>
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <cstdlib>

using namespace std;

struct RandomInteger
{
  RandomInteger(int l, int h) : low(l), high(h)
  { }//from   w ww  .  j a va2s.  c om

  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(), RandomInteger(1, 6));
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));
}

Result


Related Tutorials