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.
/*
* C++ Program to demonstrate fill_n() algorithm
*/
#include <algorithm>
#include <vector>
#include <iostream>
#include <iomanip>
void print(const std::vector <int>& v)
{
std::vector <int>::const_iterator i;
for(i = v.begin(); i != v.end(); i++)
{
std::cout << std::setw(2) << *i << " ";
}
std::cout << std::endl;
}
int main()
{
int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> v(arr, arr + sizeof(arr) / sizeof(int));
std::cout << "Vector before fill_n" << std::endl;
print(v);
std::fill_n(v.begin() + 3, 5, -1);
std::cout << "Vector after fill_n" << std::endl;
print(v);
}
$ 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.
Related Posts:
- Apply for Computer Science Internship
- Apply for Information Technology Internship
- Practice Programming MCQs
- Check C++ Books
- Apply for C++ Internship