I've never used it before.vector<struct>,现在就写一个简短的代码:
#include <vector>#include <iostream>intMain () {structSt {intA };STD:: vector<st>V V.resize (4); for(STD:: vector<st>:: Size_type i =0; I < v.size (); i++) {v.operator[] (i). A = i +1;//v[i].a = i+1;} for(inti =0; I < v.size (); i++) {STD::cout<< v[i].a <<STD:: Endl; }}
Compile successfully with VS2015, run result:
1
2
3
4
However, this is only allowed after c++11, the compiler does not allow you to write such a syntax, the vector container is not allowed to put local structure.
Further, what if there are several fields in the struct?
#include <iostream>#include <string>#include <vector>Using namespace std;struct subject {string name;intMarksintcredits;};intMain () {vector<subject> Sub;Push back new subject created with default constructor. Sub. Push_back (subject ());Vector now have1Element @Index 0, so modify it. Sub[0].name = "中文版";Add a new elementifYou want another: Sub. Push_back (subject ());Modify its name andMarks. Sub[1].name = "math"; Sub[1].marks = n; Sub. Push_back ({"Sport", 0}); Sub. Resize (8);// Sub. Emplace_back ("Sport", 0); for(inti =0; I < Sub. Size ();i++) {Std::cout << Sub[I].name << Std::endl;}}
But the above approach is not good, we should first construct the object, after the push_back may be more sensible.
Subject Subobj;
Subobj.name = S1;
Sub.push_back (Subobj);
This involves a problem, why do not use Emplace_back to replace Push_back, this is the next topic we discuss.
Vector series--creating vector of the local structure, vector of structs initialization in C + +