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

发布于 2024-09-27 01:06:25 字数 174 浏览 1 评论 0原文

假设我们有两个数组:

double *matrix=new double[100];
double *array=new double[10];

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

有什么快速解决办法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮华 2024-10-04 01:06:25

使用 std::copy 更简单:

std::copy(matrix + 80, matrix + 90, array);

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

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.

荒芜了季节 2024-10-04 01:06:25
memcpy(array, &matrix[80], 10*sizeof(double));

但是(既然你说的是 C++),使用 C++ 函数而不是旧的 C memcpy 会获得更好的类型安全性:

#include <algorithm>
std::copy(&matrix[80], &matrix[90], array);

请注意,该函数采用范围的“最后一位”指针你想使用。大多数 STL 函数都是这样工作的。

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.

温暖的光 2024-10-04 01:06:25
memcpy(array, matrix+80, sizeof(double) * 10);
memcpy(array, matrix+80, sizeof(double) * 10);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文