Home »
C++ STL
std::fill_n() function with example in C++ STL
C++ STL | std::fill_n() function: Here, we are going to learn about the fill_n() function of algorithm header in C++ STL with example.
Submitted by IncludeHelp, on May 21, 2019
C++ STL std::fill_n() function
fill_n() function is a library function of algorithm header, it is used to assign a value to the n elements of a container, it accepts an iterator pointing to the starting position in the container, n (number of elements) and a value to be assigned to the n elements, and assigns the value.
Note: To use fill_n() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.
Syntax
Syntax of std::fill_n() function
std::fill_n(iterator start, n, value);
Parameter(s)
- iterator start – an iterator pointing to the position from where we have to assign the value to the next n elements.
- n – number of elements to be assigned with the given value.
- value – a value of the same type to be assigned to the n elements.
Return value
void – it returns noting.
Sample Input and Output
Input:
vector<int> v(10);
//filling 10 elements with -1
fill(v.begin(), 10, -1);
Output:
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
C++ STL program to demonstrate use of std::fill_n() function
In this program, we are going to fill the n elements of a vector.
//C++ STL program to demonstrate use of
//std::fill_n() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
//vector
vector<int> v(10);
//filling all elements with -1
fill_n(v.begin(), 10, -1);
//printing vector elements
cout << "v: ";
for (int x : v)
cout << x << " ";
cout << endl;
//filling initial 3 elements with 100
fill_n(v.begin(), 3, 100);
//printing vector elements
cout << "v: ";
for (int x : v)
cout << x << " ";
cout << endl;
//filling rest of the elements with 200
fill_n(v.begin() + 3, 7, 200);
//printing vector elements
cout << "v: ";
for (int x : v)
cout << x << " ";
cout << endl;
return 0;
}
Output
v: -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
v: 100 100 100 -1 -1 -1 -1 -1 -1 -1
v: 100 100 100 200 200 200 200 200 200 200
Reference: C++ std::fill_n()