In practice, the vector series in c ++ -- creating vector of local structure AND vector of structs initialization

Source: Internet
Author: User

In practice, the vector series in c ++ -- creating vector of local structure AND vector of structs initialization

I have never used it beforeVector Now, write a short code:

#include 
  
   #include 
   
    int main() {    struct st { int a; };    std::vector
    
      v;    v.resize(4);    for (std::vector
     
      ::size_type i = 0; i < v.size(); i++) {        v.operator[](i).a = i + 1; // v[i].a = i+1;    }    for (int i = 0; i < v.size(); i++)    {        std::cout << v[i].a << std::endl;    }}
     
    
   
  

Compiled successfully with VS2015. Running result:
1
2
3
4

However, this is only allowed after C ++ 11. In the past, the compiler did not allow you to write such a syntax, and the local structure in the vector container was not allowed.

Furthermore, what if there are several fields in struct?

#include
  
   #include
   
    #include
    
     using namespace std;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;    sub.push_back({ "Sport", 70, 0 });    sub.resize(8);    //sub.emplace_back("Sport", 70, 0 );    for (int i = 0; i < sub.size(); i++)    {        std::cout << sub[i].name << std::endl;    }}
     
    
   
  

However, the above practice is not good. We should first construct the object and then perform push_back. It may be more wise.
Subject subObj;
SubObj. name = s1;
Sub. push_back (subObj );

This involves a question. Why don't we use emplace_back instead of push_back? This is the topic we will discuss next.

Related Article

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.