fredrik.eriksson

Coffee and a keyboard

std compliant random generator

This is a small code snippet of a random generator that can be used together with the std algorithms:

#ifndef RANDOM_GENERATOR_HPP
#define RANDOM_GENERATOR_HPP

#include <cstdlib>
#include <ctime>

template <int low, int high>
struct random_gen {
  random_gen () {
    srand(time(0));
  }
  int operator () () const {
    return rand() % high + low;
  }
};

#endif /* RANDOM_GENERATOR_HPP */

E.g. it can be used to fill an std::vector with std:generate as seen bellow:

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

#include "random_generator.hpp"

int main(int argc, char* argv[])
{
    std::vector<int> v( 12 );

    std::generate( v.begin(), v.end(), random_gen<0, 9>() );

    std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, "" ) );
    std::cout << std::endl;
}

I hope you find it useful.