std::ranges:: uninitialized_copy_n, std::ranges:: uninitialized_copy_n_result
|
定义于头文件
<memory>
|
||
|
调用签名
|
||
|
template
<
std::
input_iterator
I,
no-throw-input-iterator
O, no
-
throw
-
sentinel
-
for
<
O
>
S
>
|
(1) |
(C++20 起)
(C++26 起为 constexpr) |
|
辅助类型
|
||
|
template
<
class
I,
class
O
>
using uninitialized_copy_n_result = ranges:: in_out_result < I, O > ; |
(2) | (C++20 起) |
令 N 为 ranges:: min ( count, ranges:: distance ( ofirst, olast ) ) 。
将始于
ifirst
的范围中的
N
个元素复制到未初始化的内存区域
[
ofirst
,
olast
)
,操作等效于:
auto
ret
=
ranges::
uninitialized_copy
(
std::
counted_iterator
(
std
::
move
(
ifirst
)
, count
)
,
std::
default_sentinel
, ofirst, olast
)
;
return
{
std
::
move
(
ret.
in
)
.
base
(
)
, ret.
out
}
;
如果在初始化过程中抛出异常,已构造的对象将以未指定的顺序被销毁。
如果
[
ofirst
,
olast
)
与
ifirst
+
[
0
,
count
)
存在重叠,则行为未定义。
本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:
目录 |
参数
| ifirst | - | 待复制元素 范围 的起始位置 |
| count | - | 待复制的元素数量 |
| ofirst, olast | - | 定义目标元素 范围 的迭代器-哨兵对 |
返回值
如上所述。
复杂度
𝓞(N) 。
异常
在目标范围元素构造过程中抛出的任何异常。
注释
若输出范围的
值类型
为
平凡类型
,实现可通过使用如
ranges::copy_n
等方式提升
ranges::uninitialized_copy_n
的执行效率。
| 功能测试 宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms
|
202411L
|
(C++26) | constexpr 用于 专用内存算法 , ( 1 ) |
可能的实现
struct uninitialized_copy_n_fn { template<std::input_iterator I, no-throw-input-iterator O, no-throw-sentinel-for<O> S> requires std::constructible_from<std::iter_value_t<O>, std::iter_reference_t<I>> constexpr ranges::uninitialized_copy_n_result<I, O> operator()(I ifirst, std::iter_difference_t<I> count, O ofirst, S olast) const { auto iter = std::counted_iterator(std::move(ifirst), count); auto ret = ranges::uninitialized_copy(iter, std::default_sentinel, ofirst, olast); return {std::move(ret.in).base(), ret.out}; } }; inline constexpr uninitialized_copy_n_fn uninitialized_copy_n{}; |
示例
#include <iomanip> #include <iostream> #include <memory> #include <string> int main() { const char* stars[]{"Procyon", "Spica", "Pollux", "Deneb", "Polaris"}; constexpr int n{4}; alignas(alignof(std::string)) char out[n * sizeof(std::string)]; try { auto first{reinterpret_cast<std::string*>(out)}; auto last{first + n}; auto ret{std::ranges::uninitialized_copy_n(std::begin(stars), n, first, last)}; std::cout << '{'; for (auto it{first}; it != ret.out; ++it) std::cout << (it == first ? "" : ", ") << std::quoted(*it); std::cout << "};\n"; std::ranges::destroy(first, last); } catch (...) { std::cout << "uninitialized_copy_n exception\n"; } }
输出:
{"Procyon", "Spica", "Pollux", "Deneb"};
参见
|
(C++20)
|
将对象范围复制到未初始化的内存区域
(算法函数对象) |
|
(C++11)
|
将指定数量的对象复制到未初始化的内存区域
(函数模板) |