Vector of structs initialization

前端 未结 5 1468
终归单人心
终归单人心 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条回答
  •  伪装坚强ぢ
    2021-01-29 18:58

    Create vector, push_back element, then modify it as so:

    struct subject {
        string name;
        int marks;
        int credits;
    };
    
    
    int main() {
        vector sub;
    
        //Push back new subject created with default constructor.
        sub.push_back(subject());
    
        //Vector now has 1 element @ index 0, so modify it.
        sub[0].name = "english";
    
        //Add a new element if you want another:
        sub.push_back(subject());
    
        //Modify its name and marks.
        sub[1].name = "math";
        sub[1].marks = 90;
    }
    

    You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.

提交回复
热议问题