I have a problem when trying to delete a vector of pointers:
std::vector<float*> *v;
v = new std::vector<float*>;
v->assign(2, new float[2]);
for (int i = 0; i < 2; ++i)
{
delete[] v->at(i);
}
delete v;
I'm deleting each element from the whole vector, but I still get an assert. Can you please tell me what I'm doing wrong?
Thank you in advance.
This doesn't do what you think it does:
v->assign(2, new float[2]);
One array of size 2 is allocated, then two pointers to it are stored in the vector. When you delete, the same pointer is deleted twice.
If you want a multidimensional array, you could try std::vector< std::array< float, 2 > >. Doing new and delete yourself are a code smell. (The same goes for new vector …; that is probably not what you really want.)
THe v->assign(2, new float[2]) does the same as :
float *f = new float[2];
for(int i = 0; i < 2; i++)
v->push_back(f);
of course, that's MOST likely not what you want - you probably want:
for(int i = 0; i < 2; i++)
{
float *f = new float[2];
v->push_back(f);
}
And using new on vector is just plain wrong - just use a plain vector. Inside it, put a vector<float> - or, if you just want two elements every time, use something like:
struct f2 { float a; float b; };
vector<struct f2> v;
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