1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

how do I init a vector within a struct?

Discussion in 'C++' started by hobbyist, May 22, 2012.

  1. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    If I had something like

    Code:
    typedef struct {
        std::string some_data;
    } foo;
    
    foo init_data[] = { { "" }, { "" }, { "" } };
    
    typedef struct {
       std::string more_data;
       std::vector<foo> sfoo;
    } bar;
    Code:
    bar test = ??
    How/where would I init sfoo with the values from init_data? C++ is confusing. :D

    shabbir, does this look right?? I got a result, finally.

    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    
    typedef struct {
        std::string string_data1;
        std::string string_data2;
    } foo;
    
    foo init_data[] = {
        { "init_data1 str1", "init_data1 str2" },
        { "init_data2 str1", "init_data2 str2" },
        { "init_data3 str1", "init_data3 str2" },
        { "init_data4 str1", "init_data4 str2" },
        { "init_data5 str1", "init_data5 str2" }
    };
    
    typedef struct {
        std::string string_data1;
        std::vector<foo> struct_foo;
        std::vector<foo>::iterator it;
    } bar;
    
    int main() {
    
        bar test = { { "" }, std::vector<foo>(init_data, init_data + 5) };
    
        for(test.it = test.struct_foo.begin(); test.it != test.struct_foo.end(); ++(test.it))
            std::cout << "string data1: " << (*test.it).string_data1
                      << std::endl
                      << "string data2: " << (*test.it).string_data2
                      << "\n\n";
    
        return 0;
    }
    this stuff is enough to make bill gates give up technology and take up gardening...
     

Share This Page