用C++将一个数组中的值按逆序重新存放,例如,原来顺序为 8,6,5,4,1, 要求改为 1,4,5,6,8。
时间: 2025-01-02 17:45:58 浏览: 196
在C++中,你可以使用两层循环或者直接通过迭代器来实现数组元素的逆序排列。这里提供一种简单的双指针法的例子:
```cpp
#include <iostream>
using namespace std;
void reverseArray(int arr[], int size) {
// 初始化两个指针,一个指向开始,一个指向结束
int start = 0;
int end = size - 1;
while (start < end) {
// 交换元素的位置
swap(arr[start], arr[end]);
// 移动指针向中间靠近
start++;
end--;
}
}
int main() {
int numbers[] = {8, 6, 5, 4, 1};
int arraySize = sizeof(numbers) / sizeof(numbers[0]);
cout << "Original array: ";
for (int i : numbers) {
cout << i << " ";
}
reverseArray(numbers, arraySize);
cout << "\nReversed array: ";
for (int i : numbers) {
cout << i << " ";
}
return 0;
}
```
当你运行这个程序时,它会先打印出原始数组,然后输出逆序后的数组。
阅读全文
相关推荐

















