How to insert data into a member vector of a struct?

Asked

Viewed 45 times

0

I’m trying to build a structure composed of members that are no more than strings. The 4th member is a string array, since it needs to store more than one piece of information.

Once done I declare I vector structures. When I will insert the data inside this The compiler accuses that a primary expression is missing before "{". Detail that when I insert the data into the vector, excluding the vector string member of the structure, the program works normally.

follows the code:

struct Estrutura{
  std::string x;
  std::string y;
  std::string z;
  std::vector <std::string> result;
};

std::vector <Estrutura> vec_estrutura;

int main(){

  vec_estrutura.push_back(Estrutura{"lero", "lero", "lero", Estrutura.result.push_back("la", "li", "ho")});

 return 0;
}

1 answer

0


What you are trying to do is initialize your structure with startup lists (initialization lists) but what you’re really doing is violating language rules.

To initialize a structure that contains another structure (or vector) you must pass lists (of initialization) within lists. In this case, follows the correction:

int main() {
    vec_estrutura.push_back(Estrutura{
            "lero",
            "lero",
            "lero",
            { "la", "li", "ho" }
        });

    return 0;
}

Notice that the fourth element of the initialization list is another initialization list to initialize the vector? Simple, no?

  • Thanks friend. really had the impression of being making a fundamental mistake

Browser other questions tagged

You are not signed in. Login or sign up in order to post.