简体   繁体   中英

How to push_back elements of a vector of pointers to struct?

Below is the relevant snippet from my C++ code that is showing a warning extended initializer lists only available with -std=c++0x or -std=gnu++0x

typedef struct _A{
    string A1;
    int A2;
} A;

vector <A*> vecA;

string str1;
int k;

vecA.push_back(new A({str1, k}));  

Is there another more proper way of doing a push_back?

You need to compile with the option -std=c++0x or -std=gnu++0x when you use initializer list , or you could write a constructor

struct A {
    A(const std::string& a1, int a2)
      : A1(a1), A2(a2)
    { }

    string A1;
    int A2;
};

vecA.push_back(new A(str1, k));  

Side note: don't name your type start with underscore, also using smart pointers in vector is a better solution than naked pointer, say:

std::vector<std::unique_ptr<A>> vecA;

Normally storing values in the vector is quite convenient:

std:vector<A> vecA; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM