# C++ Algorithm Library - fill_n() Function

#### Complete Python Prime Pack for 2023

9 Courses     2 eBooks

#### Artificial Intelligence & Machine Learning Prime Pack

6 Courses     1 eBooks

#### Java Prime Pack 2023

8 Courses     2 eBooks

## Description

The C++ function std::algorithm::fill_n() assigns value to the first n elements of the sequence pointed by first.

## Declaration

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

### C++98

```template <class OutputIterator, class Size, class T>
OutputIterator fill_n (OutputIterator first, Size n, const T& val);
```

## Parameters

• first − Output iterators to the initial positions.

• n − Number of elements to fill.

• val − Value to be used to fill the range.

## Return value

Returns an iterator pointing to the element that follows the last element filled.

## Exceptions

Throws an exception if either 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::fill_n() function.

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

using namespace std;

int main(void) {
vector<int> v(5, 1);

fill_n(v.begin() + 2, 3, 4);

cout << "Vector contains following elements" << endl;

for (auto it = v.begin(); it != v.end(); ++it)
cout << *it << endl;

return 0;
}
```

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

```Vector contains following elements
1
1
4
4
4
```
algorithm.htm