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

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.