andyInCambridge andyInCambridge - 1 year ago 108
C++ Question

c++11 vector initialization in a function call

I have a question about the new shortcut way of defining vectors in c++11. Suppose I have the following class

struct Tester{

vector< vector<int> > data;

data = vector< vector<int> >();

void add(vector<int> datum){


Then, the following works as expected:

int main(){
Tester test = Tester();
vector<int> datum = vector<int>{1,2,3};

but this doesn't:

int main(){
Tester test = Tester();

Can someone please explain the difference to me? How can I do the shortcut I attempt in the second main()?

Answer Source

Your code seems to be okay but the compiler you're using is not (which seems to be old).

By the way, you're doing too much.

This is should be enough:

vector<int> datum{1,2,3}; //initialization

test.add({1,2,3}); //create vector<int> on the fly and pass it to add()

Don't forget to update your compiler.

Also, the line data = vector< vector<int> >(); is also too much. It is not needed. The vector is constructed automatically, which means you can leave the constructor of your class empty, or don't have it at all, as it doesn't do anything anyway.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download