Vector series--creating vector of the local structure, vector of structs initialization in C + +

Source: Internet
Author: User

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 + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.