开发者

Default values for arrays members of struct [duplicate]

开发者 https://www.devze.com 2023-03-19 04:48 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Intitialzing an array in a C++ class and modifiable lvalu开发者_如何学JAVAe problem
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Intitialzing an array in a C++ class and modifiable lvalu开发者_如何学JAVAe 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?


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


Changing the array to a std::vector will allow you to do simple initialization and you'll gain the other benefits of using a vector.

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


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

struct foo
{
   int array[ 10 ];
   int simpleInt;
   foo() : array(), simpleInt(0) { }
};


#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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号