Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a struct which contains vector

Tags:

c++

struct

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!

like image 885
Maverik Avatar asked Feb 02 '12 16:02

Maverik


People also ask

How do you initialize a vector inside a struct?

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; // ...

Can I make a vector of structs?

You can actually create a vector of structs!

Can we use vector inside struct?

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.


1 Answers

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.

like image 86
David Avatar answered Oct 01 '22 06:10

David