Using memcpy to copy a range of elements from an array

后端 未结 3 1187
一个人的身影
一个人的身影 2020-12-16 14:20

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

相关标签:
3条回答
  • 2020-12-16 14:35
    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.

    0 讨论(0)
  • 2020-12-16 14:43

    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.

    0 讨论(0)
  • 2020-12-16 14:54
    memcpy(array, matrix+80, sizeof(double) * 10);
    
    0 讨论(0)
提交回复
热议问题