Vector of structs initialization

前端 未结 5 1477
终归单人心
终归单人心 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:06

    You may also which to use aggregate initialization from a braced initialization list for situations like these.

    #include 
    using namespace std;
    
    struct subject {
        string name;
        int    marks;
        int    credits;
    };
    
    int main() {
        vector sub {
          {"english", 10, 0},
          {"math"   , 20, 5}
        };
    }
    

    Sometimes however, the members of a struct may not be so simple, so you must give the compiler a hand in deducing its types.

    So extending on the above.

    #include 
    using namespace std;
    
    struct assessment {
        int   points;
        int   total;
        float percentage;
    };
    
    struct subject {
        string name;
        int    marks;
        int    credits;
        vector assessments;
    };
    
    int main() {
        vector sub {
          {"english", 10, 0, {
                                 assessment{1,3,0.33f},
                                 assessment{2,3,0.66f},
                                 assessment{3,3,1.00f}
                             }},
          {"math"   , 20, 5, {
                                 assessment{2,4,0.50f}
                             }}
        };
    }
    

    Without the assessment in the braced initializer the compiler will fail when attempting to deduce the type.

    The above has been compiled and tested with gcc in c++17. It should however work from c++11 and onward. In c++20 we may see the designator syntax, my hope is that it will allow for for the following

      {"english", 10, 0, .assessments{
                             {1,3,0.33f},
                             {2,3,0.66f},
                             {3,3,1.00f}
                         }},
    

    source: http://en.cppreference.com/w/cpp/language/aggregate_initialization

提交回复
热议问题