fill() and fill_n() functions in C++ STL

A vector, once declared, has all its values initialized to zero. Following is an example code to demonstrate the same.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for displaying the default initialization
// of the vector vect[]
#include<bits/stdc++.h>
using namespace std;
  
int main() 
{
    // Creating a vector of size 8
    vector<int> vect(8);  
  
    // Printing default values
    for (int i=0; i<vect.size(); i++)
       cout << ' ' << vect[i];
}
chevron_right

Output :

0 0 0 0 0 0 0 0

 
What if we wish to initialize the vector to a specific value, say 1 ? For this, we can pass the value along with the size of the vector.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for displaying specified initialization
// of the vector vect[]
#include<bits/stdc++.h>
using namespace std;
  
int main () 
{
    // Creates a vector of size 8 with all initial
    // values as 1.
    vector<int> vect(8, 1);  
  
    for (int i=0; i<vect.size(); i++)
       cout << ' ' << vect[i];
}
chevron_right

Output :

1 1 1 1 1 1 1 1

 
What if we wish to initialize the first 4 values to say 100 and rest 6 values as 200 ?
One way to do this is to manually provide a value to each position in the vector. The other methods as provided in STL, the Standard Template Library, are fill and fill_n.
 



 

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Article Tags :
C
Practice Tags :