简体   繁体   中英

How to initialize array elements by using initializer list?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM