I have a function which I want to use to convert an array of doubles to a vector of doubles:
std::vector<double> ArrayToVector(const double* arr, int length)
{
std::vector<double> vec(length);
memcpy(&vec[0], &arr[0], length);
return vec;
};
But when I run:
int main()
{
double* x = new double[3];
x[0] = 2;
x[1] = 4;
x[2] = 6;
std::vector<double> y = ArrayToVector(x, 3);
for (int i = 0; i < 3; i++)
{
std::cout << y[i] << " ";
}
return 0;
}
I get the output:
0 0 0
Rather than
2 4 6
Why?
Your problem is memcpy expect a size in bytes, not number of elements so you need to multiply that third argument by sizeof(double) but really what you should be doing is use the constructor for vector which expects two iterators like so :
std::vector<double> y(x, x + 3);
this way you don't even need to worry about sizeof and it's shorter!
Alternatively you could use std::copy (as mentioned in my comment/the other answer but that's longer for no reason)
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