1. template <class ForwardIteratorclass T>                                         
  2. void fill(ForwardIterator first, ForwardIterator last, const T &value) {          
  3.     for(; first != last; ++first)                                                 
  4.         *first = value;                                                           
  5. }                                                                                 
  6.                                                                                   
  7. template <class OutputIteratorclass Size, class T>                              
  8. OutputIterator fill_n(OutputIterator first, Size n, const T &value) {
  9.     for(; n > 0; --n, ++first)                                                    
  10.         *first = value;                                                           
  11.     return first;                                                                 

 注:请注意输出区间的迭代器类型

当使用fill_n进行填充时,为防止 n 超过现有容器的大小,建议使用以下代码:

 
  
  1. int ia[] = {1, 2, 3}; 
  2. vector<int> iv(ia, ia + 3); 
  3. fill_n(inserter(iv, iv.begin()), 5, 0);