namespace std::ranges {
template <input_iterator I,
weakly_incrementable O>
requires indirectly_copyable<I, O>
constexpr copy_n_result<I, O>
copy_n(I first,
iter_difference_t<I> n,
O result); // (1) C++20
template <execution-policy Ep,
random_access_iterator I,
random_access_iterator O,
sized_sentinel_for<O> OutS>
requires indirectly_copyable<I, O>
copy_n_result<I, O>
copy_n(Ep&& exec,
I first,
iter_difference_t<I> n,
O result,
OutS result_last); // (2) C++26
}
概要
指定された数の要素をコピーする。
- (1): イテレータ範囲を指定する
- (2): (1)の並列アルゴリズム版。実行ポリシーを指定し、出力範囲の終端も指定する
効果
0 以上 n 未満であるそれぞれの i について、*(result + i) = *(first + i) を行う。
戻り値
copy_n_result {
.in = first + n,
.out = result + n,
}
計算量
正確に n 回代入が行われる。
例
基本的な使い方
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> v = { 3, 1, 5, 2, 4 };
std::ranges::copy_n(v.begin(), 5, std::ostream_iterator<int>(std::cout, "\n"));
}
出力
3
1
5
2
4
並列アルゴリズムの例 (C++26)
#include <algorithm>
#include <execution>
#include <iostream>
#include <vector>
int main() {
std::vector<int> src = {1, 2, 3, 4, 5};
std::vector<int> dst(5);
// 並列に先頭3要素をコピー
std::ranges::copy_n(std::execution::par, src.begin(), 3,
dst.begin(), dst.begin() + 3);
for (int x : dst) {
std::cout << x << ' ';
}
std::cout << std::endl;
}
出力
1 2 3 0 0
バージョン
言語
- C++20
処理系
- Clang: ??
- GCC: 10.1.0 ✅
- ICC: ??
- Visual C++: 2019 Update 10 ✅