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