开发者

Initializing a vector of a struct in a struct

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 ;)


In case of C++0x, you have several possibilities:

#include <vector>
#include <string>    

int main () {
    struct Person {
        Person(std::string const &name, int age) : name (name), age(age) {}
        std::string name;
        int age;
    };

    std::vector<Person> vec { {"John", 24},
                              {"Dani", 32} };

    vec.emplace_back ("Frobster", -2);
    vec.push_back ({"Little unknown rascal", 7});
}

If you don't want to write a non-default constructor, you can still do:

#include <vector>
#include <string>    

int main () {
    struct Person {
        std::string name;
        int age;
    };

    std::vector<Person> vec { {"John", 24},
                              {"Dani", 32} };

    vec.emplace_back (Person{"Frobster", -2});
    vec.push_back (Person{"Little unknown rascal", 7});
}

Though the emplace_back is superfluous then.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜