std:: copy_n
|
ヘッダーで定義
<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以降) |
[
0
,
count
)
の範囲で、
*
(
result
+
i
)
=
*
(
first
+
i
)
を実行します。
|
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以降) |
目次 |
パラメータ
| first | - | コピー元の要素範囲の先頭 |
| count | - | コピーする要素の数 |
| result | - | コピー先範囲の先頭 |
| policy | - | 使用する 実行ポリシー |
| 型要件 | ||
-
InputIt
は
LegacyInputIterator
の要件を満たさなければならない
|
||
-
OutputIt
は
LegacyOutputIterator
の要件を満たさなければならない
|
||
-
ForwardIt1, ForwardIt2
は
LegacyForwardIterator
の要件を満たさなければならない
|
||
戻り値
宛先範囲のイテレータ。 count > 0 の場合、コピーされた最後の要素の次を指し、それ以外の場合は result を指します。
計算量
count < 0 の場合、ゼロ代入。 count それ以外の場合、count回の代入。
例外
ExecutionPolicy
という名前のテンプレートパラメータを持つオーバーロードは、
以下のようにエラーを報告します:
-
アルゴリズムの一部として呼び出された関数の実行が例外をスローした場合、
ExecutionPolicyが 標準ポリシー のいずれかであるとき、 std::terminate が呼び出されます。それ以外のExecutionPolicyについては、動作は実装定義です。 - アルゴリズムがメモリの確保に失敗した場合、 std::bad_alloc がスローされます。
実装例
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; } |
`、`
`タグ内のテキスト、およびC++固有の用語は翻訳せず、元のフォーマットを保持しました。
例
#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
関連項目
|
(C++11)
|
要素の範囲を新しい場所にコピーする
(関数テンプレート) |
|
(C++20)
|
指定された数の要素を新しい場所にコピーする
(アルゴリズム関数オブジェクト) |