fill and fill_n STL Algorithms C++
The fill() and fill_n() algorithms fill a range with the value specified by val.
For fill() the range is specified by start and end.
Forfill_n(),ther range begins at start and runs for num elements.
fill Syntax:
template < class ForwardIterator, class T > void fill ( ForwardIterator first, ForwardIterator last, const T& value );
Source Code Example:
#include <iostream> #include <algorithm> #include <vector> using namespace std; typedef int type; void print_vector(vector <type> vec0) { vector <type>::iterator it; for ( it = vec0.begin( ) ; it != vec0.end( ) ; it++ ) cout << *it << " "; cout<< endl; }// print int main( ) { vector <type> vec0; for ( int i = 0 ; i <= 10 ; i++ ) vec0.push_back(i*10 ); cout<< "vector : "<<endl; print_vector(vec0); fill (vec0.begin(),vec0.end()+4,0); fill (vec0.begin()+5,vec0.end()-1,1); cout<< "vector after the replace "<<endl; print_vector(vec0); }//edn of main
Program output:
vector : 0 10 20 30 40 50 60 70 80 90 100 vector after the replace 0 0 0 0 0 1 1 1 1 1 0
fill_n Syntax:
template < class OutputIterator, class Size, class T > void fill_n ( OutputIterator first, Size n, const T& value );
Source Code Example:
#include <iostream> #include <algorithm> #include <vector> using namespace std; typedef int type; void print_vector(vector <type> vec0) { vector <type>::iterator it; for ( it = vec0.begin( ) ; it != vec0.end( ) ; it++ ) cout << *it << " "; cout<< endl; }// print int main( ) { vector <type> vec0; for ( int i = 0 ; i <= 10 ; i++ ) vec0.push_back(i*10 ); cout<< "vector : "<<endl; print_vector(vec0); fill_n (vec0.begin(),3,-1); fill_n (vec0.begin()+4,5,0); cout<< "vector after the replace "<<endl; print_vector(vec0); }//edn of main
Program Output:
vector : 0 10 20 30 40 50 60 70 80 90 100 vector after the replace -1 -1 -1 30 0 0 0 0 0 90 100