Reputation: 17223
Suppose I have a vector as such
std::vector<float*> vec;
Now I know that I need to delete the pointers inside the vector to reclaim memory. The way I know is by iterating through the vector and deleting each pointer. I wanted to know if there was a faster way of accomplishing this.
I have the following scenario
std::vector<float*> cont;
for(int i=0; i < SelectedColumns.size();i++)
{
if(someList.count()>0)
{
float *a = new float( column_cell_mapper[SelectedColumns[i]]->text().toFloat());
cont.push_back(a);
someclass.somemethod(*a) // Requires a reference
....
....
}
}
someclass.process();
Upvotes: 1
Views: 239
Reputation: 96241
EDIT:
Can you get away with reversing the order of function call vs insert to vector? For example can you do this?
float a = column_cell_mapper[SelectedColumns[i]]->text().toFloat();
someclass.somemethod(a) // Requires a reference
cont.push_back(a);
Original answer:
Just don't store the floats by pointer and use std::vector<float>
instead. For small simple types like float using the extra level of indirection doesn't buy you anything. If you really really really need to store individual floats by pointer, you can use std::unique_ptr
with C++11 or boost::shared_ptr
with previous C++ versions.
Now, if your float*
is pointing to an array of floats, still don't do it that way. Instead use a vector of vectors thusly:
std::vector<std::vector<float> > vec;
This will still automatically clean up the memory for you and enable you to concentrate on writing correct algorithms rather than spending much time making sure you clean up your memory management.
Upvotes: 3
Reputation:
Use std::unique_ptr
. When your vector goes out of scope, each float
will be destructed with no extra work from you.
std::vector<std::unique_ptr<float>> vec
If you really just want a container for a arrays of float
, see Mark B's answer and use std::vector<std::vector<float>>
instead.
Upvotes: 3