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!
To properly initialize a structure, you should write a ctor to replace the compiler provided ctor (which generally does nothing). Something like the following (with just a few attributes): struct grupo { float transX, transY; // ...
You can actually create a vector of structs!
The vector is fine. Be aware that if you copy this struct, then the vector will be copied with it. So in code with particular performance constraints, treat this struct the same way that you'd treat any other expensive-to-copy type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With