function template
<memory>

std::uninitialized_fill_n

template <class ForwardIterator, class Size, class T>
  void uninitialized_fill_n (ForwardIterator first, Size n, const T& x);
template <class ForwardIterator, class Size, class T>
  ForwardIterator uninitialized_fill_n (ForwardIterator first, Size n, const T& x);
Fill block of memory
Constructs n elements in the array pointed by first, initializing them to a value of x.

Unlike algorithm fill_n, uninitialized_fill_n constructs the objects in-place, instead of just copying the value to them. This allows to obtain fully constructed copies into a range of uninitialized memory, such as a memory block obtained by a call to get_temporary_buffer or malloc.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
template < class ForwardIterator, class Size, class T >
  void uninitialized_fill_n ( ForwardIterator first, Size n, const T& x )
{
  for (; n--; ++first)
    new (static_cast<void*>(&*first))
      typename iterator_traits<ForwardIterator>::value_type(x);
}

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
template < class ForwardIterator, class Size, class T >
  ForwardIterator uninitialized_fill_n ( ForwardIterator first, Size n, const T& x )
{
  for (; n--; ++first)
    new (static_cast<void*>(&*first))
      typename iterator_traits<ForwardIterator>::value_type(x);
  return first;
}


Parameters

first
Forward iterator to the initial position in an uninitialized sequence of at least n elements.
n
Number of elements to initialize
Size is expected to be a numeric type.
x
Value to be used to fill the range.

Return value

none
An iterator to the last element of the destination sequence where elements have been initialized.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// uninitialized_fill_n example
#include <iostream>
#include <memory>
#include <string>

int main () {
  // get block of uninitialized memory:
  std::pair <std::string*,std::ptrdiff_t>
    result = std::get_temporary_buffer<std::string>(3);

  if (result.second>0) {
    std::uninitialized_fill_n ( result.first, result.second, "c++ rocks!" );

    for (int i=0; i<result.second; i++)
      std::cout << result.first[i] << '\n';

    std::return_temporary_buffer(result.first);
  }

  return 0;
}


Output:
c++ rocks!
c++ rocks!
c++ rocks!

Complexity

Linear: Constructs (copy constructor) n objects.

See also