C++ 使用 memcpy 从数组中复制一系列元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3902215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:00:49  来源:igfitidea点击:

Using memcpy to copy a range of elements from an array

c++memcpy

提问by Eminemya

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.

我们想使用 将 10 个元素从 matrix[80:89] 复制到数组memcpy

Any quick solutions?

任何快速解决方案?

回答by James McNellis

It's simpler to use std::copy:

使用起来更简单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.

这更清晰,因为您只需指定要复制的元素范围,而不是字节数。此外,它适用于所有可以复制的类型,而不仅仅是 POD 类型。

回答by aschepler

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:

但是(因为你说 C++)你会使用 C++ 函数而不是旧的 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.

请注意,该函数采用您要使用的范围的“最后一个”指针。大多数 STL 函数以这种方式工作。

回答by Daryl Hanson

memcpy(array, matrix+80, sizeof(double) * 10);