valmo
valmo

Reputation: 1174

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?

vector<float> floatVector;
//filled floatVector here

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

Upvotes: 0

Views: 1136

Answers (5)

Bhargava
Bhargava

Reputation: 301

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

Upvotes: 0

Tom
Tom

Reputation: 5309

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));

Upvotes: 2

TravisG
TravisG

Reputation: 2373

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);

Upvotes: 0

Rocky Pulley
Rocky Pulley

Reputation: 23321

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

Upvotes: 0

littleadv
littleadv

Reputation: 20282

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

Upvotes: 4

Related Questions