Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate_n with constructor which takes two arguments

Hi I'm trying to do the following:

struct A {
A(int i, int j){}
}

int startValue = 10;
vector<A> v;
generate_n(back_inserter(v), 10, ???;

How can I "deliver" the two arguments startValue and the functor rand?

Thank you

like image 432
melbic Avatar asked Jan 27 '11 16:01

melbic


1 Answers

Since a generator is a function object, you can instantiate the generator and provide arguments to its constructor:

class MyGenerator
{
private:
   int startValue;
public:
   MyGenerator(int startValue): startValue(startValue) {}

   // generate an instance of A
   A operator()() 
   {
       return A(startValue, rand()); // or whatever you were planning to do here...                
   }
};

...
//down in your code (added Fred's sugestion)
generate_n(back_inserter(v), 10, MyGenerator(startValue));

Then each time you generate you can use startValue and rand to calculate the next parameters to use to construct your A object.

like image 153
Doug T. Avatar answered Sep 18 '22 01:09

Doug T.