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 o开发者_高级运维ut. Could someone explain to me and help me figure out why it won't let me add this vector to my vector?
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.
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. :-)
Clarifying a bit on GMan's response above
The following code also throws the same error as you have got while doing a push_back.
typedef float MYBUF[3];
int main(){
MYBUF m1;
MYBUF m2(m1); // Same Error as in OP
}
This is exactly what the vector::push_back does with any T. It tries to make a copy (and hence the term copyable) of the input argument and such a copy is not allowed by the C++ language for array types.
Not sure how well it will suit you, but you could experiment with some less direct solution, like the following (which compiles without error):
#include <iostream>
#include <vector>
typedef float M3DVector3f[3];
struct X
{
X(M3DVector3f& p) { x_[0] = p[0]; x_[1] = p[1]; x_[2] = p[2]; }
operator M3DVector3f&() { return x_; }
M3DVector3f x_;
};
int main()
{
M3DVector3f v = { 1, 2, 3 };
std::vector<X> xs;
xs.push_back(v);
}
精彩评论