generate_n |
function template |
template <class OutputIterator, class Size, class Generator>
void generate ( OutputIterator first, Size n, Generator gen ); |
<algorithm> |
Generate values for sequence with function
Sets the value of the first n elements in the sequence pointed by first to the value returned by successive calls to gen.
The behavior of this function template is equivalent to:
template <class OutputIterator, class Size, class Generator>
void generate ( OutputIterator first, Size n, Generator gen )
{
for (; n>0; --n) *first++ = gen();
}
|
Parameters
- first
- Output iterators to the initial positions in a sequence of at least n elements.
- n
- Number of elements to set value to.
Its type is an integral type or some other type convertible to it.
- gen
- Generator function that takes no arguments and returns some value to be stored as element value. This can either be a pointer to a function or an object whose class overloads operator().
Return value
none
Example
// generate_n example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int current(0);
int UniqueNumber () { return ++current; }
int main () {
vector<int> myvector (9);
vector<int>::iterator it;
generate (myvector.begin(), myvector.end(), UniqueNumber);
cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
|
A possible output:
myvector contains: 1 2 3 4 5 6 7 8 9
|
Complexity
Linear: Invokes
gen and assigns that value,
n times.
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 (template function) |