Generate_n with a constructor that takes two arguments

Hi, I am 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” two startValue arguments and a rand functor?

thanks

+6
c ++ constructor
source share
1 answer

Since the generator is an object of the function, 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 sugestion) generate_n(back_inserter(v), 10, MyGenerator(startValue)); 

Then, each time you create, you can use startValue and rand to calculate the following parameters that will be used to create your object A.

+10
source share

All Articles