Reputation: 2398
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!
Upvotes: 12
Views: 11079
Reputation: 116
If you're not using C++11 (so you can't use Mankarse's suggestion), boost can help:
C c = { {0.1, 0.2}, {boost::assign::list_of(1.0)(2.0)(3.0)} };
Upvotes: 3
Reputation: 31435
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)} };
Upvotes: 0
Reputation: 28178
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.
Upvotes: 1
Reputation: 18627
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) );
Upvotes: -1
Reputation: 84
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.
Upvotes: 0
Reputation: 40613
You can initialise C
in a very similar way in C++ to in C:
C c = {{0.3, 0.01}, {{14.2, 18.1, 0.0, 3.2}}};
Upvotes: 11