fill() Function in C++

This C++ program demonstrates the fill() algorithm. The program uses function fill() to fill a container within specified iterator ranges. The function takes iterator to the beginning and end of the container and the value to be filled.

Here is the source code of the C++ program which demonstrates the fill() 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() 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" << std::endl;
  25.     print(v);
  26.     std::fill(v.begin() + 4, v.end() - 3, -1);
  27.     std::cout << "Vector after fill" << std::endl;
  28.     print(v);
  29. }

$ a.out
Vector before fill
 0  1  2  3  4  5  6  7  8  9 
Vector after fill
 0  1  2  3 -1 -1 -1  7  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 & discussions at Telegram SanfoundryClasses.