std::ranges::copy_n, std::ranges::copy_n_result
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::input_iterator I, std::weakly_incrementable O > requires std::indirectly_copyable<I, O> |
(1) | (C++20 起) |
輔助型別 |
||
template< class I, class O > using copy_n_result = ranges::in_out_result<I, O>; |
(2) | (C++20 起) |
1) 從始於 first 的範圍複製恰好 n 個值到始於 result 的範圍,透過對
[
0,
n)
中的每個整數 i 執行 *(result + i) = *(first + i)。如果 result 位於範圍 [
first,
first + n)
之內,則行為未定義(這種情況下可以改用 ranges::copy_backward)。本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first | - | 要複製的元素範圍的起始 |
n | - | 要複製的元素數量 |
result | - | 目標範圍的開頭 |
[編輯] 返回值
ranges::copy_n_result{first + n, result + n} 或更正式地,一個型別為 ranges::in_out_result 的值,它包含一個等於 ranges::next(first, n) 的 input_iterator
迭代器和一個等於 ranges::next(result, n) 的 weakly_incrementable
迭代器。
[編輯] 複雜度
恰好 n 次賦值。
[編輯] 注意
實踐中,如果值型別為 TriviallyCopyable 且迭代器型別滿足 contiguous_iterator
,std::ranges::copy_n
的實現可能避免多次賦值並使用批次複製函式,例如 std::memmove。或者,這種複製加速可以在編譯器的最佳化階段注入。
當複製重疊範圍時,當向左複製(目標範圍的起始在源範圍之外)時,std::ranges::copy_n
是合適的;而當向右複製(目標範圍的結束在源範圍之外)時,std::ranges::copy_backward 是合適的。
[編輯] 可能的實現
struct copy_n_fn { template<std::input_iterator I, std::weakly_incrementable O> requires std::indirectly_copyable<I, O> constexpr ranges::copy_n_result<I, O> operator()(I first, std::iter_difference_t<I> n, O result) const { for (; n-- > 0; (void)++first, (void)++result) *result = *first; return {std::move(first), std::move(result)}; } }; inline constexpr copy_n_fn copy_n{}; |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <string> #include <string_view> int main() { const std::string_view in{"ABCDEFGH"}; std::string out; std::ranges::copy_n(in.begin(), 4, std::back_inserter(out)); std::cout << std::quoted(out) << '\n'; out = "abcdefgh"; const auto res{std::ranges::copy_n(in.begin(), 5, out.begin())}; const auto i{std::distance(std::begin(in), res.in)}; const auto j{std::distance(std::begin(out), res.out)}; std::cout << "in[" << i << "] = '" << in[i] << "'\n" << "out[" << j << "] = '" << out[j] << "'\n"; }
輸出
"ABCD" in[5] = 'F' out[5] = 'f'
[編輯] 參閱
(C++20)(C++20) |
將一個範圍的元素複製到一個新位置 (演算法函式物件) |
(C++20) |
以逆序複製一個範圍的元素 (演算法函式物件) |
(C++20)(C++20) |
複製一個範圍的元素,忽略那些滿足特定條件的元素 (演算法函式物件) |
(C++20)(C++20) |
複製一個範圍,同時用另一個值替換滿足特定條件的元素 (演算法函式物件) |
(C++20) |
建立一個反轉後的範圍副本 (演算法函式物件) |
(C++20) |
複製並旋轉一個範圍的元素 (演算法函式物件) |
(C++20) |
建立一個不含連續重複元素的某個元素範圍的副本 (演算法函式物件) |
(C++20) |
將一個範圍的元素移動到一個新位置 (演算法函式物件) |
(C++20) |
以逆序將一個範圍的元素移動到一個新位置 (演算法函式物件) |
(C++11) |
將一定數量的元素複製到一個新位置 (函式模板) |