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()?
Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.
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.
If you want to avoid data copying:
#include <vector> #include <iostream> using namespace std; struct Tester { vector< vector<int> > data; Tester() { data = vector< vector<int> >(); } void add(vector<int> && datum) { data.push_back(std::move(datum)); } }; int main() { Tester test = Tester(); test.add(vector<int>{1,2,3}); for(const auto &v : test.data[0]) std::cout << v << std::endl; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With