Vector of structs initialization

前端 未结 5 1471
终归单人心
终归单人心 2021-01-29 18:52

I want know how I can add values to my vector of structs using the push_back method

struct subject
{
  string name;
  int marks;
  int credits;
};

         


        
5条回答
  •  梦毁少年i
    2021-01-29 19:14

    You cannot access elements of an empty vector by subscript.
    Always check that the vector is not empty & the index is valid while using the [] operator on std::vector.
    [] does not add elements if none exists, but it causes an Undefined Behavior if the index is invalid.

    You should create a temporary object of your structure, fill it up and then add it to the vector, using vector::push_back()

    subject subObj;
    subObj.name = s1;
    sub.push_back(subObj);
    

提交回复
热议问题