C++ 反转数组

17 Mar 2025 | 6 分钟阅读

本节将讨论在 C++ 编程语言中反转数组的不同方法。数组的反转意味着改变给定数组元素的顺序。这种技术将数组的最后一个元素反转到第一个位置,第一个元素变成最后一个。然而,这个过程一直持续到数组的所有字符或元素完全反转。

例如,数组包含 'H'、'E'、'L'、'L'、'O' 等元素,当我们反转数组的所有元素时,它会返回反转后的数组 'O'、'L'、'L'、'E'、'H'。这样,数组中的所有字符都被反转了。

Reverse an Array in C++

反转数组的不同方法

以下是在 C++ 编程语言中获取反转数组的各种方法。

  • 使用 for 循环反转数组
  • 使用 reverse() 函数反转数组
  • 使用用户定义函数反转数组
  • 使用指针反转数组
  • 使用递归函数反转数组

使用 for 循环反转数组的程序

让我们创建一个程序,使用 C++ 中的 for 循环反转数组的元素。

Program1.cpp

输出

Please, enter the total no. you want to enter: 6
 Enter the element 1: 78
 Enter the element 2: 12
 Enter the element 3: 54
 Enter the element 4: 24
 Enter the element 5: 7
 Enter the element 6: 90

 Reverse all elements of the array:
90 7 24 54 12 78

使用 reverse() 函数反转数组的程序

让我们考虑一个例子,使用 C++ 中的 reverse() 函数打印数组的反转。

Program2.cpp

输出

2 5 90 21 78 34

使用用户定义函数反转数组的程序

让我们考虑一个例子,使用 C++ 中的用户定义函数显示数组元素的反转。

Program3.cpp

输出

Number of elements to be entered:
7
 Enter the array elements:
45
32
89
21
78
34
65
 Elements are:
45 32 89 21 78 34 65
 The reverse of the given array is:
65 34 78 21 89 32 45

使用指针反转数组的程序

让我们考虑一个例子,演示使用 C++ 中的指针反转数组元素。

Program4.cpp

输出

No. of array elements to be entered:
6
 Enter the elements: 45
32
89
63
4
6
 Entered elements of the array are:

        45      32      89      63      4       6
 The reversed array elements are:

         6
         4
         63
         89
         32
         45

使用递归函数反转数组

让我们创建一个程序,使用 C++ 中的递归函数反转数组元素。

Program5.cpp

输出

Original elements of the arrays
20 34 5 8 1 78
 Reverse elements of the array are:
78 1 8 5 34 20