Vector of structs initialization

前端 未结 5 1547
终归单人心
终归单人心 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 19:13

    After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element

    But I found new to do this using default_structure_element like following...

    #include 
    typedef long long ll;
    using namespace std;
    
    typedef struct subject {
      string name;
      int marks;
      int credits;
    }subject;
    
    int main(){
      subject default_subject;
      default_subject.name="NONE";
      default_subject.marks = 0;
      default_subject.credits = 0;
    
      vector  sub(10,default_subject);         // default_subject to initialize
    
      //to check is it initialised
      for(ll i=0;i

    Then I think its good to way to initialize a vector of the struct, isn't it?

提交回复
热议问题