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::generate_n - cpprefjp C++日本語リファレンス

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

最終更新日時: 2026年09月19日 21時31分51秒 (JST)
rotarymars が更新

履歴 編集

function template
<algorithm>

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

namespace std::ranges {
  template <input_or_output_iterator O,
            copy_constructible F>
    requires invocable<F&> && indirectly_writable<O, invoke_result_t<F&>>
  constexpr O
    generate_n(O first,
               iter_difference_t<O> n,
               F gen);                  // (1) C++20
}

概要

出力の範囲へ関数の結果を n 個書き込む。

  • (1): イテレータ範囲を指定する

効果

n が 1 以上の場合、[first,first + n) のそれぞれのイテレータについて関数オブジェクト gen を呼び出し、その戻り値を代入する。

そうでない場合、何もしない。

戻り値

n が 1 以上の場合、first + n が返される。
そうでない場合、first が返される。

計算量

n が 1 以上の場合、n 回の gen の呼び出しと代入が行われる。

そうでない場合、何もしない。

例

基本的な使い方

#include <algorithm>
#include <iostream>
#include <iterator>

int main() {
  // 2 の累乗の値を生成して出力する
  int n = 1;
  std::ranges::generate_n(std::ostream_iterator<int>(std::cout, ","), 10, [&n]{ auto t = n; n *= 2; return t; });
}

出力

1,2,4,8,16,32,64,128,256,512,

バージョン

言語

  • C++20

処理系

  • Clang: 16.0.6 ✅
  • GCC: 10.1.0 ✅
  • Visual C++: 2019 Update 10 ✅

参照

  • N4861 25 Algorithms library
  • P3179R9 C++ parallel range algorithms
    • C++26でranges::generate_nの並列アルゴリズム版が追加された
  • LWG Issue 4492. std::generate and std::ranges::generate wording is unclear for parallel algorithms
    • 並列実行時の「successive(連続した)」評価という意味付けが不明確であるため、P3179R9で追加されたranges::generate_nの並列アルゴリズム版はC++26で削除された(C++29での再検討が予定されている)
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.