C++ で配列要素の値をクリアする方法
- 
          
            ビルトインの fill()メソッドを使用して C++ の配列要素をクリアする
- 
          
            std::fill()アルゴリズムを用いて C++ で配列の要素をクリアする
- 
          
            配列の要素をクリアするには fill_n()アルゴリズムを使用する
 
この記事では、C++ で配列要素の値をクリアする方法について、複数のメソッドを紹介します。
ビルトインの fill() メソッドを使用して C++ の配列要素をクリアする
    
コンテナ std::array はその要素を操作する複数の組み込みメソッドを提供します。これは配列オブジェクトの各要素に与えられた値を代入します。任意の要素型で配列を作成しても fill() 関数を使ってコンテナの各要素に値を渡して代入することができることに注意してください。
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
using std::array;
using std::cout;
using std::endl;
using std::fill;
using std::fill_n;
int main() {
  array<int, 10> nums{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  cout << "| ";
  for (const auto &item : nums) {
    cout << item << " | ";
  }
  cout << endl;
  nums.fill(0);
  cout << "| ";
  for (const auto &item : nums) {
    cout << item << " | ";
  }
  return EXIT_SUCCESS;
}
出力:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
std::fill() アルゴリズムを用いて C++ で配列の要素をクリアする
あるいは、STL <algorithm> ライブラリで定義されている std::fill アルゴリズムを利用することもできます。このメソッドは範囲ベースのオブジェクトに対して呼び出され、その要素に与えられた値を代入します。最初の 2つの引数として要素の範囲を渡し、3 番目の引数で代入する値を指定します。C++17 バージョンからは、オプションの引数として実行ポリシーを指定することも可能になりました (詳細はこちらを参照してください)。
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
using std::array;
using std::cout;
using std::endl;
using std::fill;
using std::fill_n;
int main() {
  array<int, 10> nums{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  cout << "| ";
  for (const auto &item : nums) {
    cout << item << " | ";
  }
  cout << endl;
  std::fill(nums.begin(), nums.end(), 0);
  cout << "| ";
  for (const auto &item : nums) {
    cout << item << " | ";
  }
  return EXIT_SUCCESS;
}
出力:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
配列の要素をクリアするには fill_n() アルゴリズムを使用する
これは、与えられた値で変更する必要のある複数の要素を受け取る点を除いて、上記のメソッドと似ています。この場合、size() メソッドの戻り値を指定することで、上記のコード例と同じ動作をするようにしています。なお、このメソッドにも実行ポリシータグが適用されることに注意してください。
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
using std::array;
using std::cout;
using std::endl;
using std::fill;
using std::fill_n;
int main() {
  array<int, 10> nums{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  cout << "| ";
  for (const auto &item : nums) {
    cout << item << " | ";
  }
  cout << endl;
  std::fill_n(nums.begin(), nums.size(), 0);
  cout << "| ";
  for (const auto &item : nums) {
    cout << item << " | ";
  }
  return EXIT_SUCCESS;
}
出力:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
        チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
    
著者: 胡金庫
    
