Name
generate function template — Fills a range with values returned from a function
Synopsis
template<typename FwdIter, typename Generator>
void generate(FwdIter first, FwdIter last, Generator gen);
The generate
function
template fills the sequence [first
, last
) by assigning the result of calling
gen( )
repeatedly.
Example
Example 13-2 shows a simple way to fill a sequence with successive integers.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
// Generate a series of objects, starting with "start".
template <typename T>
class series {
public:
series(const T& start) : next(start) {}
T operator( )( ) { return next++; }
private:
T next;
};
int main( )
{
std::vector<int> v;
v.resize(10);
// Generate integers from 1 to 10. std::generate(v.begin( ), v.end( ), series<int>(1));
// Print the integers, one per line.
std::copy(v.begin( ), v.end( ),
std::ostream_iterator<int>(std::cout, "\n"));
}
Technical Notes
Complexity is linear: gen
is called exactly last -
first times.
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.