std::ranges::uninitialized_copy_n, std::ranges::uninitialized_copy_n_result
定義於標頭檔案 <memory> |
||
呼叫簽名 (Call signature) |
||
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)。
[編輯] 異常
在目標範圍內構造元素時丟擲的任何異常。
[編輯] 注意
如果輸出範圍的值型別是TrivialType,實現可以透過使用例如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) |
將一定數量的物件複製到未初始化記憶體區域 (函式模板) |