Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize array elements by using initializer list?

Tags:

c++

visual-c++

Im trying something like this (which doesnt compile):

struct mystruct {
    somestruct arr[4];
    mystruct(somestruct val) : arr[0](val), arr[1](val), arr[2](val), arr[3](val) {}
};

How is this best done in c++ ?

Note: i might want to set only some of the array elements with this method.

like image 543
Rookie Avatar asked Dec 30 '11 17:12

Rookie


1 Answers

In C++11, if you want to set all the elements:

mystruct(somestruct val) : arr{val,val,val,val} {}

In C++03, or C++11 if you only want to set some elements:

mystruct(somestruct val) {
    arr[0] = val;
    arr[1] = val;
    arr[2] = val;
    arr[3] = val;
}
like image 126
Mike Seymour Avatar answered Oct 14 '22 06:10

Mike Seymour