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 起) (constexpr 自 C++26 起) |
辅助类型 |
||
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
的效率。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__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) |
将多个对象复制到未初始化的内存区域 (函数模板) |