Default values for arrays members of struct [dupli

2019-04-29 23:47发布

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?

4条回答
唯我独甜
2楼-- · 2019-04-29 23:58

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) { }
};
查看更多
Bombasti
3楼-- · 2019-04-30 00:01

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) {};
};
查看更多
冷血范
4楼-- · 2019-04-30 00:04

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
};
查看更多
Juvenile、少年°
5楼-- · 2019-04-30 00:11
#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.

查看更多
登录 后发表回答