开发者

c++ stl copy function proper memory management

Just on the following code do I need to allocate memory with new for floatArray or will the copy function allocate memory for me?

Also is it okay to copy a constant vector to an array this way? Why?

vecto开发者_开发知识库r<float> floatVector;
//filled floatVector here

float *floatArray = new float[floatVector.size()];
copy(floatVector.begin(),floatVector.end(),floatArray);          
delete[] floatArray;


std::copy doesn't allocate memory, you should do it yourself.


If you don't want to allocate the array first then you may use a back_inserter iterator to push elements one by one into certain containers. For some containers this is less efficient (I think) but can be very handy sometimes.

#include<iterator>
#include<vector>
#include<deque>

std::vector<float> floatVector(10,1.0);
std::deque<float>  floatDeque; //memory not allocated

//insert elements of vector into deque.
std::copy(floatVector.begin(), floatVector.end(), std::back_inserter(floatDeque));


copy will not allocate for you, so yes you need to allocate it.


std::copy copies by using the arguments assignment ("=") operator or the arguments copy constructor (this is probably implementation dependent, I'm not sure right now). It does nothing but iterate through the range beginning at param.begin() to param.end() and do something like:

while (first!=last) *result++ = *first++;

Thus, you need to allocate the memory necessary yourself. Otherwise it will create undefined behaviour.

Is it OK to copy a constant vector to an array this way? Depends on what you want to do. Generally, it's fine, since the values are transferred to the target by value, not by reference, hence const-correctness is not broken.

For example, this works fine:

std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
const std::vector<int> constvec(vec);

int *arrray = new int[2];
std::copy(constvec.begin(),constvec.end(),arrray);


copy function never allocate memory but you have to allocate memory for static datastructures but for dynamic datastructures, it'll allocate memory automatically.

and this process is not good but its better to use another vector instead of that floatarray

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜