简体   繁体   中英

Initialize a struct which contains vector

I'm looking for a method for initializing a complex struct which contains vector in a single row.

For example if I have this structure:

struct A{
  double x;
  double y;
};
struct B{
  double z;
  double W;
};
struct C{
  A a;
  B b;
};

I can initialize C in this way: C c = {{0.0,0.1},{1.0,1.1}};

But what If I have to initialize a struct like this?

struct A{
  double x;
  double y;
};
struct B{
  vector<double> values;
};
struct C{
  A a;
  B b;
};

I have to do it in a single row because I want to allow the users of my application to specify in a single field all the initial values. And of course, I would prefer a standard way to do it and not a custom one.

Thanks!

您可以在C ++中以非常类似的方式初始化C到C:

C c = {{0.3, 0.01}, {{14.2, 18.1, 0.0, 3.2}}};

如果你没有使用C ++ 11(所以你不能使用Mankarse的建议),boost可以帮助:

C c = { {0.1, 0.2}, {boost::assign::list_of(1.0)(2.0)(3.0)} };

You could do this:

C obj = { { 0.0, 0.1f }, std::vector<double>( 2, 0.0 ) };

But obviously it's not ideal since all the values in your vector need to be the same.

The question is how to initialize B in the second example?

You cannot initialize a vector like this:

std::vector<int> v = { 1, 2, 3 }; // doesn't work

You can do this

int data[] = { 1, 2, 3 };
std::vector<int> v( &data[0], &data[0]+sizeof(data)/sizeof(data[0]));

(there are nicer ways to do that). That isn't a "one-liner" though.

This works and I have tested it:

template< typename T >
struct vector_builder
{
     mutable std::vector<T> v;
     operator std::vector<T>() const { return v; }
};

template< typename T, typename U >
vector_builder<T>& operator,(vector_builder<T>& vb, U const & u )
{
vb.v.push_back( u );
return vb;
}

struct B
{
  vector<double> v;

};

B b = { (vector_builder(),1.1,2.2,3.3,4.4) };

C c = { {1.1, 2.2 }, {(vector_builder(),1.1,2.2,3.3,4.4)} };

You'll just have to use one of the constructors if you don't have the new C++11 initialization syntax.

    C c = {{1.0, 1.0}, {std::vector<double>(100)}};

The vector above has 100 elements. There's no way to initialize each element uniquely in a vector's construction.

You could do...

 double values[] = {1, 2, 3, 4, 5};
 C c = {{1.0, 1.0}, {std::vector<double>(values, values+5)}};

or if you always know the number of elements use a std::array which you can initialize the way you want.

struct C {
    A a;
    B b;
    C(double ta[2], vector<double> tb) {
        a = A(ta[0],ta[1]);    // or a.x = ta[0]; a.y = ta[1]
        b = tb;
    }
};

then you can initialize with something like

C c = C( {0.0, 0.1} , vector<double> bb(0.0,5) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM