Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need help adding an array to a vector in C++

I'm following along with the OpenGL Super Bible 5th edition, and they define a vector(vector as in math) as

typedef float   M3DVector3f[3];

I'm trying to add an instance of this to an std::vector(the 're sizable array' in c++), however I keep getting an error saying:

array initialization needs curly braces

Full Error

The way I defined the std::vector and the way I'm adding to it is:

std::vector<M3DVector3f> vertices;

float vertex[3];
sscanf_s(line.c_str(), "%*s %f %f %f", &vertex[0], &vertex[1], &vertex[2]);

M3DVector3f v = {vertex[0], vertex[1], vertex[3]};

vertices.push_back(v);

I've gathered that the problem is with the vertices.push_back(v) call, because I don't get an error when I comment that out. Could someone explain to me and help me figure out why it won't let me add this vector to my vector?

like image 212
krej Avatar asked Nov 23 '10 02:11

krej


2 Answers

Arrays cannot be (directly) copied or assigned, and standard containers requires types to be copyable and assignable.

However, you can (and probably should) do this instead:

struct M3DVector3f // a basic vector class
{
    float x;
    float y;
    float z;
};

Which is copyable and just as usable.

like image 63
GManNickG Avatar answered Sep 25 '22 19:09

GManNickG


For starters, vertex[3] above should be vertex[2] as vertex[3] lies outside the upper bound of the array. However, that is not the crux of the issue here. The template instantiation of vector is being done with an array type. There is no default copy constructor, per se, for array types that will perform any copy deeper than the simple pointer copy. You may find that this works better if instead you try:

std::vector<M3DVector3f*> vertices;
M3DVector3f* v = new M3DVector3f;

sscanf_s(line.c_str(), "%*s %f %f %f", &((*v)[0]), &((*v)[1]), &((*v)[2]));

vertices.push_back(v);

There may be another, more elegant solution utilizing smart pointers to clean up each entry in the vector when you go to destroy it later. :-)

like image 34
Dave Avatar answered Sep 25 '22 19:09

Dave