std::fill() and std::fill_n() functions in C++

Hello everyone, in this post we will learn about std::fill() and std::fill_n() functions in C++. These functions are used with vectors to fill values. Let’s discuss more on this topic further in this tutorial.

C++ std::fill() and std::fill_n() functions

Normally, when we initialize a vector without providing any value, all of its values are by default initialized as zero. If we provide value while initializing the vector, all of its values equate to that value. See the below code for better understanding.

#include<bits/stdc++.h>

using namespace std;

int main()
{
  vector<int> vec1(5);
  cout << "Values for vec1(5) are:\n";
  for(int i=0; i<vec1.size(); i++)
  {
    cout << vec1[i] << " ";
  }
  
  vector<int> vec2(5, 4);
  cout << "\n\nValues of vec2(5, 4) are:\n";
  
  for(int i=0; i<vec2.size(); i++)
  {
    cout << vec2[i] << " ";
  }
  
  
  return 0;	
}

 

Output:

Values for vec1(5) are:
0 0 0 0 0

Values of vec2(5, 4) are:
4 4 4 4 4

Now let’s say we want to initialize the first 3 values of the vector to a particular value, say 9. We can do it using fill() and fill_n() functions. Let’s see how.

std::fill()

The syntax for fill() function is as follows:

std::fill(iterator begin, iterator end, value);

The return type for this function is void.

The above function fills the given value within the given range as you can see in the output of the below program.

The below implementation describes well the std::fill() function. Here is the code.

#include<bits/stdc++.h>

using namespace std;

int main()
{
  vector<int> vec(5);

  fill(vec.begin(), vec.begin()+3, 9);
  cout << "Values for vec are:\n";
  for(int i=0; i<vec.size(); i++)
  {
    cout << vec[i] << " ";
  }
  
  return 0;	
}

Output:

Values for vec are:
9 9 9 0 0

std::fill_n()

The syntax for fill_n() function is given here.

std::fill_n(iterator begin, n, value);

The return for this function is void.

std::fill_n() function fills n number of elements in the vector with the given value. See the below code to understand the working of this function.

#include<bits/stdc++.h>

using namespace std;

int main()
{
  vector<int> vec(5);

  fill_n(vec.begin(), 3, 9);
  cout << "Values for vec are:\n";
  for(int i=0; i<vec.size(); i++)
  {
    cout << vec[i] << " ";
  }
  
  return 0;	
}

Output:

Values for vec are:
9 9 9 0 0

Thank you.

Also read: Access Elements from a Vector in C++

Leave a Reply

Your email address will not be published. Required fields are marked *