namespace std::ranges {
template <class I, class O>
using uninitialized_copy_n_result = in_out_result<I, O>;
template <input_iterator I,
no-throw-forward-iterator O,
no-throw-sentinel<O> S>
requires constructible_from<iter_value_t<O>, iter_reference_t<I>>
uninitialized_copy_n_result<I, O>
uninitialized_copy_n(
I ifirst,
iter_difference_t<I> n,
O ofirst,
S olast
); // (1) C++20
template <input_iterator I,
no-throw-forward-iterator O,
no-throw-sentinel<O> S>
requires constructible_from<iter_value_t<O>, iter_reference_t<I>>
constexpr uninitialized_copy_n_result<I, O>
uninitialized_copy_n(
I ifirst,
iter_difference_t<I> n,
O ofirst,
S olast
); // (1) C++26
template <execution-policy Ep,
random_access_iterator I,
random_access_iterator O,
sized_sentinel_for<O> S>
requires constructible_from<iter_value_t<O>, iter_reference_t<I>>
uninitialized_copy_n_result<I, O>
uninitialized_copy_n(
Ep&& exec,
I ifirst,
iter_difference_t<I> n,
O ofirst,
S olast
); // (2) C++26
}
概要
未初期化領域のイテレータ範囲[ofirst, ofirst + n)を配置newでイテレータ範囲[ifirst, ifirst + n)の対応する要素から初期化してコピー出力する。
- (1): イテレータ範囲を指定する
- (2): (1)の並列アルゴリズム版。実行ポリシーを指定する
テンプレートパラメータ制約
- (1):
Iがinput_iteratorであるOがno-throw-forward-iteratorであるSがOに対する例外を投げない番兵であるOの要素型が、Iの要素型を引数として構築可能である
事前条件
- イテレータ範囲
[ofirst, olast)がifirst + [0, n)と重ならないこと
効果
以下と等価である:
auto t = uninitialized_copy(counted_iterator(ifirst, n),
default_sentinel, ofirst, olast);
return {std::move(t.in).base(), t.out};
例外
呼び出すコンストラクタなどから例外が送出された場合、その例外がこの関数の外側に伝播される前に、その時点で構築済のオブジェクトは全て未規定の順序で破棄される。すなわち、例外が送出された場合は初期化対象領域は未初期化のままとなる。
例
基本的な使い方
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
int main()
{
const std::vector<int> v = {1, 2, 3};
std::allocator<int> alloc;
// メモリ確保。
// この段階では、[p, p + size)の領域は未初期化
const std::size_t size = 3;
int* p = alloc.allocate(size);
// 未初期化領域pを初期化しつつ範囲vから要素をコピー
std::ranges::uninitialized_copy_n(v.begin(), size, p, p + size);
// pの領域が初期化され、かつvからpに要素がコピーされているか確認
std::for_each(p, p + size, [](int x) {
std::cout << x << std::endl;
});
// 要素を破棄
std::ranges::destroy_n(p, size);
// メモリ解放
alloc.deallocate(p, size);
}
出力
1
2
3
並列アルゴリズムの例 (C++26)
#include <iostream>
#include <memory>
#include <vector>
#include <execution>
int main() {
std::vector<int> src = {1, 2, 3, 4, 5};
std::allocator<int> alloc;
int* dst = alloc.allocate(3);
// 並列に3要素を未初期化領域へコピー
std::ranges::uninitialized_copy_n(
std::execution::par, src.begin(), 3, dst, dst + 3);
for (int i = 0; i < 3; ++i) {
std::cout << dst[i] << ' ';
}
std::cout << std::endl;
std::ranges::destroy(dst, dst + 3);
alloc.deallocate(dst, 3);
}
出力
1 2 3
バージョン
言語
- C++20
処理系
- Clang: 16.0 ✅
- GCC: 10.2.0 ✅
- Visual C++: 2019 Update 10 ✅