C++ Algorithm Library - generate_n() Function

Description

The C++ function std::algorithm::generate_n() assigns the value returned by successive calls to gen to the first n elements of the sequence pointed by the first.

Declaration

Following is the declaration for std::algorithm::generate_n() function form std::algorithm header.

C++11

```template <class OutputIterator, class Size, class Generator>
OutputIterator generate_n (OutputIterator first, Size n, Generator gen);
```

Parameters

• first − Output iterator to the initial position.

• n − Number of values to generate.

• gen − Generator function that is called with no arguments and returns some value.

Return value

Returns an an iterator which points to the element that follows the last element whose value has been generated.

Exceptions

Throws exception if either gen function or the element assignment or an operation on an iterator throws exception.

Please note that invalid parameters cause undefined behavior.

Linear.

Example

The following example shows the usage of std::algorithm::generate_n() function.

```#include <iostream>
#include <algorithm>

using namespace std;

int main(void) {
int arr[10] = {0, 0, 0, 0, 0, -100};

/* assign value to only first 5 elements */
auto it = generate_n(arr, 5, rand);

cout << "First five random numbers are" << endl;

for (int i = 0; i < 10; ++i)
cout << arr[i] << endl;

cout << endl;

cout << "Iterator points to " << *it << endl;

return 0;
}
```

Let us compile and run the above program, this will produce the following result −

```First five random numbers are
1804289383
846930886
1681692777
1714636915
1957747793
-100
0
0
0
0
Iterator points to -100
```
algorithm.htm