Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11 vector initialization in a function call

Tags:

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()?

like image 404
andyInCambridge Avatar asked Dec 20 '12 15:12

andyInCambridge


People also ask

What is the correct way to initialize vector in C++?

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.


2 Answers

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.

like image 135
Nawaz Avatar answered Sep 19 '22 14:09

Nawaz


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; } 
like image 32
foxfireee Avatar answered Sep 17 '22 14:09

foxfireee