function template
<algorithm>
std::generate_n
template <class OutputIterator, class Size, class Generator> void generate_n (OutputIterator first, Size n, Generator gen);
template <class OutputIterator, class Size, class Generator> OutputIterator generate_n (OutputIterator first, Size n, Generator gen);
Generate values for sequence with function
Assigns the value returned by successive calls to gen to the first n elements of the sequence pointed by first.
The behavior of this function template is equivalent to:
1 2 3 4 5 6 7 8
|
template <class OutputIterator, class Size, class Generator>
void generate_n ( OutputIterator first, Size n, Generator gen )
{
while (n>0) {
*first = gen();
++first; --n;
}
}
|
Parameters
- first
- Output iterators to the initial positions in a sequence of at least n elements that support being assigned a value of the type returned by gen.
- n
- Number of values to generate.
This value shall not be negative.
If negative, the function does nothing.
Size shall be (convertible to) an integral type.
- gen
- Generator function that is called with no arguments and returns some value of a type convertible to those pointed by the iterators.
This can either be a function pointer or a function object.
Return value
none
An iterator pointing to the element that follows the last element whose value has been generated.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// generate_n example
#include <iostream> // std::cout
#include <algorithm> // std::generate_n
int current = 0;
int UniqueNumber () { return ++current; }
int main () {
int myarray[9];
std::generate_n (myarray, 9, UniqueNumber);
std::cout << "myarray contains:";
for (int i=0; i<9; ++i)
std::cout << ' ' << myarray[i];
std::cout << '\n';
return 0;
}
|
A possible output:
myarray contains: 1 2 3 4 5 6 7 8 9
|
Complexity
Linear in n: Calls gen and performs an assignment for each element.
Data races
The n first objects at the range pointed by first are modified (each object is modified exactly once).
Exceptions
Throws if any of gen, the element assignments or the operations on iterators throws.
Note that invalid arguments cause undefined behavior.
See also
- generate
- Generate values for range with function (function template)
- fill_n
- Fill sequence with value (function template)
- for_each
- Apply function to range (function template)