Default Values ​​for Structure Array Elements

Possible duplicate:
Integrating an array into a C ++ class and mutable problem with lvalue

As you can see from this question, you can give a ctor structure to force its members to receive default values. How would you start giving a default value for each element of the array inside the structure.

struct foo { int array[ 10 ]; int simpleInt; foo() : simpleInt(0) {}; // only initialize the int... } 

Is there a way to do this on a single line, similar to how you would do this to initialize an int?

+4
source share
4 answers

The new C ++ standard has this way:

 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 yet support this syntax, you can always assign an array to each element:

 struct foo { int array[ 10 ]; int simpleInt; foo() : simpleInt(0) { for(int i=0; i<10; ++i) array[i] = i; } }; 

EDIT: single-line solutions in pre-2011 C ++ require different types of containers, such as a C ++ vector (which is preferable anyway) or a 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) {}; }; 
+5
source

Changing the array to std :: vector will allow you to perform simple initialization, and you will get other benefits of using the vector.

 #include <vector> struct foo { std::vector<int> array; int simpleInt; foo() : array(10, 0), simpleInt(0) {}; // initialize both }; 
+4
source

If you just want to initialize the array by default (setting the built-in types to 0), you can do this as follows:

 struct foo { int array[ 10 ]; int simpleInt; foo() : array(), simpleInt(0) { } }; 
+2
source
 #include <algorithm> struct foo { int array[ 10 ]; int simpleInt; foo() : simpleInt(0) { std::fill(array, array+10, 42); } }; 

or use std::generate(begin, end, generator); where the generator is up to you.

+1
source

All Articles