The problem is that transform
simply not the right choice for the task. The goal of transform
is to take some inputs, transform them in a specific way, and create output for each of these inputs.
In this case, you have no input. transform
makes sense if the values ββin the vector were (one way or another) based on the values ββin any existing vector.
generate_n
is really the right solution to the problem - it is designed to call some function / functor N times, producing N results and assigning them to the output iterator (and its successors) that you supply. Since it is designed to generate values ββ(instead of converting existing values), the function / functor does not accept input, and you do not need to provide a "fake" input.
As for the dummy argument, the need for it is probably a pretty good sign that (as in this case) you are using the wrong algorithm, and simply shouldn't do it.
However, you sometimes find yourself in the opposite situation: you want to use an algorithm that does not provide an argument, but you want to have an argument. For example, suppose you wanted to be able to set the numbers in your array to a random number with some lower and / or upper bound specified by the user. In this case, you want to specify the boundaries that will be passed to your random function, but there are no conditions for either generate
or generate_n
.
In this case, you have two options. One of them is bind
(originally boost::bind
, but now included in C ++ 11). As a rule, I prefer to use a functor, and pass the argument to ctor:
class gen_random { int lower; int upper; public: gen_random(int lower = 0, int upper = RAND_MAX) : lower(lower), upper(upper) {} int operator() { return rand_range(lower, upper); }; int main() { std::vector<int> rand_ints; std::generate_n(std::back_inserter(rand_ints), 10, gen_random(1, 6)); return 0; }