使用指针交换而不引用数组C++
Swap using a pointer without referring the array C++
所以我需要交换数组的第 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);
相关文章:
- 关于引用数组位置的问题
- 使用指针交换而不引用数组C++
- 对于Boost.Propertytree,有没有办法使用JSON点表示法来引用数组元素?
- 如何在递归函数中调用引用数组?
- 动态指针引用数组由三元运算符返回值,但有异常
- 为什么没有 std::string 构造函数来引用数组
- 指针/引用数组
- 错误 C2234:引用数组是非法的
- 引用数组的方法
- 通过引用数组值进行交换
- 引用数组涉及的技术问题
- 引用数组的函数调用
- 从其他类中的类引用数组
- 如何使用变量名称引用数组位置
- 在 OpenGL 中呈现三角形结构引用数组
- 如何取消引用数组元素(C++)
- c++引用数组数组(指针到指针?)
- 指向指针的指针如何能够引用数组
- C++取消引用数组
- c++中引用数组中对象的共享指针