Apache C++ Standard Library Reference Guide

## generate(), generate_n()

Library:  Algorithms

`Function`

No Entries

### Summary

Algorithm that assigns each element in a range a value produced by repeated application of the given function object

### Synopsis

```#include <algorithm>

namespace std {
template <class ForwardIterator, class Generator>
void generate(ForwardIterator start, ForwardIterator finish,
Generator gen);

template <class OutputIterator, class Size, class Generator>
void generate_n(OutputIterator start, Size n,
Generator gen);
}
```

### Description

A value-generator function returns a value each time it is invoked. The algorithms generate() and generate_n() assign each element in the sequence [start, finish) or [start, start + n) the return value of the generator function gen(). The function gen() takes no arguments. (gen() can be a function or a class with an operator() defined that takes no arguments.)

generate_n() assumes that all iterators in the range [start, start + n] are dereferenceable, unless start is an insert iterator.

### Complexity

The generate() and generate_n() algorithms invoke gen() and assign its return value exactly finish - start (or n) times.

### Example

```//
// generate.cpp
//

#include <algorithm>    // for generate, generate_n
#include <iostream>     // for cout, endl
#include <vector>       // for vector

// Value generator simply doubles the current value
// and returns it.
template <class T>
class generator
{
T val_;
public:
generator(const T &val) : val_ (val) { }
T operator()() {
return val_ += val_;
}
};

int main ()
{
// Typedef for convenience.
typedef std::vector<short,
std::allocator<short> > vector;

vector::value_type arr[4] = { 1, 2, 3, 4 };

// Set up two vectors.
vector v1(arr, arr + sizeof arr / sizeof *arr);
vector v2 = v1;

// Set up one empty vector.
vector v3;

// Create a generator function object.
generator<vector::value_type> gen(1);

// Generate values for all of v1.
std::generate(v1.begin(), v1.end(), gen);

// Generate values for first 3 of v2.
std::generate_n(v2.begin(), 3, gen);

// Use back_insert_iterator to generate 5 values for v3.
std::generate_n(std::back_inserter(v3), 5, gen);

// Copy all three to cout.
std::ostream_iterator<vector::value_type, char,
std::char_traits<char> > out(std::cout, " ");

std::copy(v1.begin(), v1.end(), out);
std::cout << std::endl;

std::copy(v2.begin(), v2.end(), out);
std::cout << std::endl;

std::copy(v3.begin(), v3.end(), out);
std::cout << std::endl;

// Generate 3 values into cout.
std::generate_n(out, 3, gen);
std::cout << std::endl;

return 0;
}

Program Output:
```
```2 4 8 16
2 4 8 4
2 4 8 16 32
2 4 8
```