如何使用 C++ 中的 STL 反轉陣列?
下面我們來看看如何在 C++ 中使用 STL 函式反轉陣列。如果陣列為 A = [10, 20, 30, 40, 50, 60],那麼結果將為 B = [60, 50, 40, 30, 20, 10]。要反轉,我們可以使用標頭檔案 <algorithm> 中的一個名為 reverse() 的函式。如下所示:
例項
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50, 60};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Array before reverse: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
reverse(arr, arr + n);
cout << "\nArray after reverse: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}輸出
Array before reverse: 10 20 30 40 50 60 Array after reverse: 60 50 40 30 20 10
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP