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

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

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

履歴 編集

function template
<algorithm>

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

namespace std::ranges {
  template <class T,
            output_iterator<const T&> O>
  constexpr O
    fill_n(O first,
           iter_difference_t<O> n,
           const T& value);             // (1) C++20
  template <class O,
            class T = iter_value_t<O>>
    requires output_iterator<O, const T&>
  constexpr O
    fill_n(O first,
           iter_difference_t<O> n,
           const T& value);             // (1) C++26

  template <execution-policy Ep,
            random_access_iterator O,
            class T>
    requires indirectly_writable<O, const T&>
  O fill_n(Ep&& exec,
           O first,
           iter_difference_t<O> n,
           const T& value);             // (2) C++26
}

概要

指定された値で出力の範囲に n 個を書き込む。

  • (1): イテレータ範囲を指定する
  • (2): (1)の並列アルゴリズム版。実行ポリシーを指定する

効果

n が 1 以上の場合は [first,first + n) 内の全ての要素に value を代入し、そうでない場合は何もしない。

戻り値

n が 1 以上の場合は first + n、そうでない場合は first を返す。

計算量

n が 1 以上の場合は n 回、そうでない場合は 0 回の代入を行う。

備考

  • (1) :
    • C++26 : valueパラメータとして波カッコ初期化{}を受け付ける
      std::vector<T> v;
      std::ranges::fill_n(v.begin(), n, {a, b});
      

例

基本的な使い方

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

int main() {
  // 値3を10個出力する
  std::ranges::fill_n(std::ostream_iterator<int>(std::cout, ","), 10, 3);
}

出力

3,3,3,3,3,3,3,3,3,3,

波カッコ初期化を入力として使用する (C++26)

#include <algorithm>
#include <iostream>
#include <vector>

struct Point {
  int x;
  int y;

  bool operator==(const Point& other) const = default;
};

int main() {
  std::vector<Point> v(5);

  // 先頭3個の要素を値{1, 2}で埋める
  std::ranges::fill_n(v.begin(), 3, {1, 2});

  for (const Point& p : v) {
    std::cout << p.x << "," << p.y << std::endl;
  }
}

出力

1,2
1,2
1,2
0,0
0,0

並列アルゴリズムの例 (C++26)

#include <algorithm>
#include <execution>
#include <iostream>
#include <vector>

int main() {
  std::vector<int> v(5);

  // 並列に先頭3要素を42で埋める
  std::ranges::fill_n(std::execution::par, v.begin(), 3, 42);

  for (int x : v) {
    std::cout << x << ' ';
  }
  std::cout << std::endl;
}

出力

42 42 42 0 0

バージョン

言語

  • C++20

処理系

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

参照

  • N4861 25 Algorithms library
  • P2248R8 Enabling list-initialization for algorithms
    • C++26で波カッコ初期化 (リスト初期化) に対応した
  • 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.