Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values for arrays members of struct [duplicate]

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?

like image 946
ALOToverflow Avatar asked Jul 11 '11 15:07

ALOToverflow


People also ask

Can struct members have default values?

Default values MAY be defined on struct members. Defaults appear at the end of a field definition with a C-like = {value} pattern.

What is the default value of structure members in C?

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 .

Are array members deeply copied?

The point to note is that the array members are not shallow copied, compiler automatically performs Deep Copy for array members..

What is default value of array in C++?

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.


1 Answers

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) {};
};
like image 95
Cubbi Avatar answered Nov 07 '22 09:11

Cubbi