Difference between revisions of "cpp/memory/uninitialized fill n"
From cppreference.com
m (correctness fix in the example) |
(Fixed includes.) |
||
Line 44: | Line 44: | ||
#include <memory> | #include <memory> | ||
#include <string> | #include <string> | ||
+ | #include <tuple> | ||
int main() | int main() |
Revision as of 03:37, 6 May 2013
Defined in header <memory>
|
||
template< class ForwardIt, class Size, class T > void uninitialized_fill_n( ForwardIt first, Size count, const T& value ) |
||
Copies the given value value
to the first count
elements in an uninitialized memory area beginning at first
. The elements in the uninitialized area are constructed using copy constructor.
Contents |
Parameters
first | - | the beginning of the range of the elements to initialize |
count | - | number of elements to construct |
value | - | the value to construct the elements with |
Type requirements | ||
-ForwardIt must meet the requirements of LegacyForwardIterator.
|
Return value
Iterator to the element past the last element copied.
Complexity
Linear in count
Possible implementation
template< class ForwardIt, class Size, class T > void uninitialized_fill_n(ForwardIt first, Size count const T& value) { typedef typename std::iterator_traits<ForwardIt>::value_type Value; for (; count > 0; ++first, --count) { ::new (static_cast<void*>(&*first)) Value(value); } return first; } |
Example
Run this code
#include <algorithm> #include <iostream> #include <memory> #include <string> #include <tuple> int main() { std::string* p; std::size_t sz; std::tie(p, sz) = std::get_temporary_buffer<std::string>(4); std::uninitialized_fill_n(p, sz, "Example"); for (std::string* i = p; i != p+sz; ++i) { std::cout << *i << '\n'; i->~basic_string<char>(); } std::return_temporary_buffer(p); }
Output:
Example Example Example Example