Possible Duplicate:
Intitialzing an array in a C++ class and modifiable lvalue problem
As seen in this question, it's possible to give a ctor to a struct to make it members get default values. How would you proceed to give a default value to every element of an array inside a struct.
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0) {}; // only initialize the int...
}
Is there some way to make this in one line similar to how you would do to initialize an int?
Default values MAY be defined on struct members. Defaults appear at the end of a field definition with a C-like = {value} pattern.
For variables of class types and other reference types, this default value is null . However, since structs are value types that cannot be null , the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null .
The point to note is that the array members are not shallow copied, compiler automatically performs Deep Copy for array members..
All others are initialized to 0. A for loop can be used to initialize an array with one default value that is not zero. This is shown below. In the above example, all the array elements are initialized to 5.
Thew new C++ standard has a way to do this:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : array{1,2,3,4,5,6,7,8,9,10}, simpleInt(0) {};
};
test: https://ideone.com/enBUu
If your compiler does not support this syntax yet, you can always assign to each element of the array:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0)
{
for(int i=0; i<10; ++i)
array[i] = i;
}
};
EDIT: one-liner solutions in pre-2011 C++ require different container types, such as C++ vector (which is preferred anyway) or boost array, which can be boost.assign'ed
#include <boost/assign/list_of.hpp>
#include <boost/array.hpp>
struct foo
{
boost::array<int, 10> array;
int simpleInt;
foo() : array(boost::assign::list_of(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)),
simpleInt(0) {};
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With