存在“循环memcpy”吗?

3

有没有一种方法可以使用memcpy(或类似函数)从一个循环数组复制到另一个循环数组,但带有偏移量?我可以使用循环实现,但我想更快地实现它。

显然,内存中没有“循环”这个概念,但我希望你能理解我的意思。

谢谢大家。

这就是我想要实现的,但不想使用for循环。

uint8_t array1[SIZE];
uint8_t array2[SIZE];

uint8_t offset = SOME_OFFSET;
uint8_t offsetAdj;

for (uint8_t index = 0; index < SIZE; index++)
{
    offsetAdj = offset + index;
   if (offsetAdj >= SIZE)
      offsetAdj -= SIZE;
   array2[offsetAdj] = array1[index];
}

8
你不需要循环,只需要精确地使用两个单独的 memcpy 调用。 - Konrad Rudolph
2个回答

7

你已经使用你的代码实现了std::rotate_copy

uint8_t array1[SIZE];
uint8_t array2[SIZE];
uint8_t offset = SOME_OFFSET;

std::rotate_copy( std::begin(array1),
                  std::begin(array1) + offset,
                  std::end  (array1),
                  std::begin(array2) );

std::rotate_copymemcpy 不同,它可以处理非连续容器和非平凡可复制类型的容器。


非常有用,谢谢 - 它能复制自己吗?也就是说,通过偏移量来移动内存内容? - Jim
如果 [first,n_first) 或 [n_first,last) 不是有效范围,或者源范围和目标范围重叠,则行为未定义。(请参见:std::rotate) - Mooing Duck
正如明智的 Mooing Duck 所提到的那样,应使用 std::rotate 进行原地旋转。 - Drew Dormann

0
这是一个简单的工作示例。
#include <stdio.h>
#include <string.h>
#include <stdint.h>


int main() {
    
    uint8_t SIZE = 8;
    uint8_t array1[SIZE];
    uint8_t array2[SIZE];
    uint8_t offset = 3;
    uint8_t i = 0; 
  
  // Initialize the arrays with some values
  for (i = 0; i < SIZE; i++) {
    array1[i] = i;
    array2[i] = 0;
  }

  // Copy the elements of array1 into array2 with an offset of 3
  memcpy(&array2[offset], array1, SIZE - offset);
  memcpy(array2, &array1[SIZE - offset], offset);

  // Print the contents of array1 and array2 to verify the copy
    
  for (i = 0; i < SIZE; i++)
    printf("%d ", array1[i]);
  
  printf("\n");
  
  for (i = 0; i < SIZE; i++)
    printf("%d ", array2[i]);
  
  return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接