fill_n

Assigns a new value to a specified number of elements in a range beginning with a particular element.

template<class OutputIterator, class Size, class Type>
   void fill_n(
      OutputIterator _First, 
      Size _Count, 
      const Type& _Val
   ); 

Parameters

  • _First
    An output iterator addressing the position of the first element in the range to be assigned the value _Val.

  • _Count
    A signed or unsigned integer type specifying the number of elements to be assigned the value.

  • _Val
    The value to be assigned to elements in the range [_First, _First + _Count).

Remarks

The destination range must be valid; all pointers must be dereferenceable, and the last position is reachable from the first by incrementation. The complexity is linear with the size of the range.

fill_n has two related forms:

For information on how these functions behave, see Checked Iterators.

Example

// alg_fill_n.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <iostream>

int main() {
   using namespace std;
   vector <int> v1;
   vector <int>::iterator Iter1;

   int i;
   for ( i = 0 ; i <= 9 ; i++ )
      v1.push_back( 5 * i );
   
   cout << "Vector v1 = ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")" << endl;

   // Fill the last 5 positions with a value of 2
   fill_n( v1.begin( ) + 5, 5, 2 );

   cout << "Modified v1 = ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")" << endl;
}

Output

Vector v1 = ( 0 5 10 15 20 25 30 35 40 45 )
Modified v1 = ( 0 5 10 15 20 2 2 2 2 2 )

Requirements

Header: <algorithm>

Namespace: std

See Also

Reference

Standard Template Library

Other Resources

<algorithm> Members