mercredi 27 juillet 2016

Initializing std::vector

I have this code, that compiled perfectly on gcc (c++11):

static const std::vector< std::vector<double> > vect = 
{
  {1,1,1}, 
  {1,1,-1}, 
  {-1,1,-1}, 
  {-1,1,1}, 
  {1,-1,1}, 
  {1,-1,-1}, 
  {-1,-1,-1}, 
  {-1,-1,1}
};

However, when I tried to compiled in on VS2012, I first got an error of unsupported initializer list. I fixed it by installing the November CTP and using the new compiler. However, now I'm getting this error:

error C2440: 'initializing' : cannot convert from 'initializer-list' to 'std::vector<std::vector<double,std::allocator<_Ty>>,std::allocator<std::vector<_Ty,std::allocator<_Ty>>>>'
1>          with
1>          [
1>              _Ty=double
1>          ]
1>          No constructor could take the source type, or constructor overload resolution was ambiguous

I've seen people saying to use an array and use the range constructor, but this is usually for a single dimensional vector.

I could probably do the same, but that would mean I will need to initialize all vectors 1 by 1 first, and then initialize the second dimension of the vector by pushing vectors, like this:

std::array<double,3> v0_init = {1,1,1};
std::vector<double> v0(v0_init.begin(), v0_init.end());
std::array<double,3> v1_init = {1,1,-1};
std::vector<double> v1(v1_init.begin(), v1_init.end());
...
std::vector< std::vector<double> > vect;
vect.push_back(v0);
vect.push_back(v1);
...

But I don't think it's a clean way to do it, and it's also not easy to find the vectors value (other people may have to access, modify or even add vectors, and I don't want them to have to copy/paste some of the code to add some new vectors to the list).

Is there a better way to do it ?

Thank you.

Aucun commentaire:

Enregistrer un commentaire