Search code examples
c++c++11initializationlist-initialization

Cannot use initialization list on two overlapping structs


I want to use initialization list to initial the variable p1 to simplify things for me. But it's not happening please help. Code is almost self explainatory.

struct word_t {
    int in;
    string word;
    int out;
    word_t(int i, string w, int o): in(i),word(w),out(o) {}
};


struct para_t {
    std::vector<word_t> words;
};

struct song_t { 
    std::vector<para_t> paras;
};    

int main()
{
    //SONG
    std::vector<song_t> song;

    para_t p1{ { 0, "We", 10 }, { 11, "are", 14 } , { 15, "the", 18 } 
    , { 19, "World", 22 } }; // CANNOT INITIALIZE LIKE SO 

    p1.words.push_back(word_t(0, "World", 10));   // THIS WORKS


}

Solution

  • You need one more {}, i.e.

    para_t p1{ { { 0, "We", 10 }, { 11, "are", 14 } , { 15, "the", 18 } , { 19, "World", 22 } } };
    //       ^                                                                                  ^ <- for para_t
    //         ^                                                                              ^   <- for para_t::words
    //           ^             ^                                                                  <- for elements (i.e. word_t) in vector