Say we have two arrays:
double *matrix=new double[100];
double *array=new double[10];
And we want to copy 10 elements from matrix[80:89] to array using memcpy
.
Any quick solutions?
Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe.
A simple loop is slightly faster for about 10-20 bytes and less (It's a single compare+branch, see OP_T_THRES ), but for larger sizes, memcpy is faster and portable.
memmove() is similar to memcpy() as it also copies data from a source to destination.
memcpy is usually naive - certainly not the slowest way to copy memory around, but usually quite easy to beat with some loop unrolling, and you can go even further with assembler.
It's simpler to use std::copy
:
std::copy(matrix + 80, matrix + 90, array);
This is cleaner because you only have to specify the range of elements to be copied, not the number of bytes. In addition, it works for all types that can be copied, not just POD types.
memcpy(array, &matrix[80], 10*sizeof(double));
But (since you say C++) you'll have better type safety using a C++ function rather than old C memcpy
:
#include <algorithm>
std::copy(&matrix[80], &matrix[90], array);
Note that the function takes a pointer "one-past-the-end" of the range you want to use. Most STL functions work this way.
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