GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::ranges::copy_n - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. algorithm
  3. copy_n

最終更新日時: 2026年09月11日 13時06分31秒 (JST)
Akira Takahashi が更新

履歴 編集

function template
<algorithm>

std::ranges::copy_n(C++20)

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 ✅
  • Visual C++: 2019 Update 10 ✅

参照

  • N4861 25 Algorithms library
  • P3179R9 C++ parallel range algorithms
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.