使用指针交换而不引用数组C++

Swap using a pointer without referring the array C++

本文关键字:引用 数组 C++ 指针 交换      更新时间:2023-10-16

所以我需要交换数组的第 2 行和第 3 行。我们的教授让我们使用一维数组并使用指针而不是二维数组。我们不能只引用指针来引用数组。我不知道该怎么做。

int numbers[25] = { 1,3,5,7,9 , -2,-4,-6, -8, -10 , 3,3,3,3,3 , 55, 77, 99, 22, 33, -15, -250, -350, -450, -550 };

这个数组应该看起来像这样:

1     3     5     7     9 
-2    -4    -6    -8   -10   // i need to swap this row
3     3     3     3     3   // for this row
55    77    99    22    33 
-15  -250  -350  -450  -550 
This is how i need to print it
1     3     5     7     9 
3     3     3     3     3
-2    -4    -6    -8   -10  
55    77    99    22    33 
-15  -250  -350  -450  -550

注意:这不是我的全部硬件作业,只是我卡住的地方。

为什么不尝试这样的事情:

constexpr std::size_t rowLength = 5u;
const auto beginRow2 = std::begin(numbers) + (rowLength * 2);
const auto endRow2 = std::begin(numbers) + (rowLength * 3);
const auto beginRow3 = std::begin(numbers) + (rowLength * 3);
std::swap_ranges(beginRow2, endRow2, beginRow3);

这是惯用C++,可以很容易地调整为提供一个通用函数,该函数接受一维容器、行长度和要交换的两行。

只需定义一个临时数组:

int tmp_row[5];

保存第三行:

int bytes = sizeof(tmp_row);
memcpy(tmp_row, &numbers[10], bytes);

然后适当填写第二行和第三行:

memcpy(&numbers[10], &numbers[5], bytes);
memcpy(&numbers[5], tmp_row, bytes);