0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】配列を特定の値で初期化する

Posted at
2024/05/14

配列の要素は{}で初期化することができる。

class MyClass
{
    MyClass() : array_{0, 1, 2, 3} {}
    int array_[4];
};

これを変更して、任意の配列サイズに対応する方法を考えてみる。基本的な考え方は以下の通りで、テンプレート引数をそのまま配列に渡せればよい。

template <size_t... iota>
MyClass(???) : array_{iota...} {}

そしてこの ??? にはstd::index_sequenceを使うことができる。

template <size_t... iota>
MyClass(std::index_sequence<iota...>) : array_{iota...} {}

また、std::make_index_sequence<4>{}とすればindex_sequence<0, 1, 2, 3>を作ることができる。配列サイズはstd::extentで取得できるので、まとめると以下のようになる。

class MyClass
{
    MyClass() : MyClass{std::make_index_sequence<std::extent_v<decltype(array_)>>{}} {}
 
    template <size_t... iota>
    MyClass(std::index_sequence<iota...>) : array_{iota...} {}
 
    int array_[4];
};

ちなみに配列を全て同じ値で初期化したい場合は、(iota, x)とすればよい。

template <size_t... iota>
MyClass(std::index_sequence<iota...>) : array_{(iota, 777)...} {}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?