将数组中的值复制到另一个不同的大小

copy values from array into another different size

本文关键字:另一个 复制 数组      更新时间:2023-10-16

我有一个数组A[8]={0};而另一个数组B[20]={0};

我想把所有的值从B[12…20]移到A[0…8]。我怎样才能准确地更改索引?有公式吗?所以B[12]->A[0]B[13]-->A[1]

谢谢。

使用std::copy。它也适用于用户定义的类型:

std::copy(B+12, B+20, A);

或者,在c++11中,

std::copy(std::next(B,12), std::end(B), std::begin(A));

您应该在这里使用std::copy,无论数组中的元素类型如何,它都能正常工作(说到这一点,您没有显示那种类型——问题的语法无效)。

std::copy(B + 12, B + 20, A);

只需编写一个循环

int offset = 12;
int lenA = 8;
for(int i=0; i < lenA; i++) {
   A[i] = B[i+offset];
}

memcpy(A, B + 12, 8 * sizeof(A[0]));应该能做到这一点。

假设A和B都是同一类型。