std::copy_n
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
template< class InputIt, class Size, class OutputIt > OutputIt copy_n( InputIt first, Size count, OutputIt result ); |
(1) | (C++11 起) (C++20 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt1, class Size, class ForwardIt2 > |
(2) | (C++17 起) |
1) 從始於 first 的範圍中精確複製 count 個值到始於 result 的範圍。形式上,對於
[
0,
count)
中的每個整數 i,執行 *(result + i) = *(first + i)。 形式上允許範圍重疊,但這會導致不可預測的結果順序。
2) 同 (1),但根據 policy 執行。
僅當滿足以下所有條件時,此過載才參與過載決議
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 為 true。 |
(C++20 前) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> 為 true。 |
(C++20 起) |
目錄 |
[edit] 引數
first | - | 要複製的元素範圍的起始 |
count | - | 要複製的元素數量 |
result | - | 目標範圍的開頭 |
policy | - | 要使用的 執行策略 |
型別要求 | ||
-InputIt 必須滿足 LegacyInputIterator 的要求。 | ||
-OutputIt 必須滿足 LegacyOutputIterator 的要求。 | ||
-ForwardIt1, ForwardIt2 必須滿足 LegacyForwardIterator 的要求。 |
[edit] 返回值
目標範圍中的迭代器,如果 count > 0 則指向最後一個複製元素之後,否則為 result。
[edit] 複雜度
如果 count < 0 則零次賦值;否則 count 次賦值。
[edit] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 如果作為演算法一部分呼叫的函式執行丟擲異常,且
ExecutionPolicy
是 標準策略 之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[edit] 可能的實現
template<class InputIt, class Size, class OutputIt> constexpr //< since C++20 OutputIt copy_n(InputIt first, Size count, OutputIt result) { if (count > 0) { *result = *first; ++result; for (Size i = 1; i != count; ++i, (void)++result) *result = *++first; } return result; } |
[edit] 示例
執行此程式碼
#include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <string> #include <vector> int main() { std::string in {"1234567890"}; std::string out; std::copy_n(in.begin(), 4, std::back_inserter(out)); std::cout << out << '\n'; std::vector<int> v_in(128); std::iota(v_in.begin(), v_in.end(), 1); std::vector<int> v_out(v_in.size()); std::copy_n(v_in.cbegin(), 100, v_out.begin()); std::cout << std::accumulate(v_out.begin(), v_out.end(), 0) << '\n'; }
輸出
1234 5050
[edit] 參閱
(C++11) |
將一個範圍的元素複製到一個新位置 (函式模板) |
(C++20) |
將一定數量的元素複製到一個新位置 (演算法函式物件) |