andyInCambridge andyInCambridge - 1 month ago 6
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;

Tester(){
data = vector< vector<int> >();
}

void add(vector<int> datum){
data.push_back(datum);
}

};


Then, the following works as expected:

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


but this doesn't:

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


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

Answer

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.