反转C ++中的数组

本文展示了使用C ++编码以降序反转的数组,其中最高索引因此通过在循环中遍历数组而交换为最低索引。

示例

#include <iostream>
#include <algorithm>
using namespace std;
void reverseArray(int arr[], int n){
   for (int low = 0, high = n - 1; low < high; low++, high--){
      swap(arr[low], arr[high]);
   }
   for (int i = 0; i < n; i++){
      cout << arr[i] << " ";
   }
}
int main(){
   int arrInput[] = { 11, 12, 13, 14, 15 };
   cout<<endl<<"Array::";
   for (int i = 0; i < 5; i++){
      cout << arrInput[i] << " ";
   }
   int n = sizeof(arrInput)/sizeof(arrInput[0]);
   cout<<endl<<"Reversed::";
   reverseArray(arrInput, n);
   return 0;
}

输出结果

作为投标中提供的整数类型的数组,将其按降序反转,以下结果为;

Array::11 12 13 14 15
Reversed::15 14 13 12 11