fill_n() Function in C++
Posted by Superadmin on August 10 2022 05:30:58

fill_n() Function in C++

 

 

This C++ program demonstrates the fill_n() algorithm. The program uses function fill_n() to fill some continous positions in a container. The function takes iterator from which the values are to be filled, the number of positions to be filled and the value to be filled.

 

Here is the source code of the C++ program which demonstrates the fill_n() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate fill_n() algorithm
  3.  */
  4. #include <algorithm>
  5. #include <vector>
  6. #include <iostream>
  7. #include <iomanip>
  8.  
  9. void print(const std::vector <int>& v)
  10. {
  11.     std::vector <int>::const_iterator i;
  12.     for(i = v.begin(); i != v.end(); i++)
  13.     {
  14.         std::cout << std::setw(2) <<  *i << " ";
  15.     }
  16.     std::cout << std::endl;
  17. }
  18.  
  19. int main()
  20. {
  21.     int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  22.     std::vector<int> v(arr, arr + sizeof(arr) / sizeof(int));
  23.  
  24.     std::cout << "Vector before fill_n" << std::endl;
  25.     print(v);
  26.     std::fill_n(v.begin() + 3, 5, -1);
  27.     std::cout << "Vector after fill_n" << std::endl;
  28.     print(v);
  29. }

 

$ a.out
Vector before fill_n
 0  1  2  3  4  5  6  7  8  9 
Vector after fill_n
 0  1  2 -1 -1 -1 -1 -1  8  9