I know how to get a struct in a struct working but what I can't get to work is vector of a struct in a struct.
Creating a vector of a struct on a normal basis works for example with:
vector<struct> str1(100);
but how do I do that if I have the following code:
struct attribures {
string name;
bool value;
};
struct thing {
string name;
double y;
int x;
vector<attributes> attrib;
};
How can I now initialize elements of the vector? One thing I could do is something like the following:
attributes a;
objec.attrib.push_back(a); // object is a struct of type thing
But that solution doesnt seem that elegant to me. Is there anyway that is more of the first kind?
EDIT: sorry for the confusion. The "100" was actually just an example and in the second example it was actually also just an example, which is supposed to show how it could be done but doesn't seem very elegant to me.
Perhaps add a constructor to attributes:
struct attributes{
attributes(const string& name, bool value) : name(name), value(value) {}
string name;
bool value;
};
and then:
object.attrib.push_back(attributes("foo", true));
Your question is not clear, so I'm trying to guess what you want to do. If you want that thing is always initialized with 100 elements, you need to use a constructor (I also initialized x and y as they are undefined by default, so it's good to initialize them):
struct thing {
string name;
double y;
int x;
vector<attributes> attrib;
thing() : y(0), x(0), attrib(100) {}
};
If you want to build a vector of 100 elements with a default value:
attributes a;
a.name = "fOO";
std::vector<attributes> attrib(100, a);
This will give you a vector of 100 elements having "foo" as name.
And of course you can combine both examples ;)
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