如何在 C++ 中使用 STL 反轉一個向量?
本教程將討論一個示例程式,讓你瞭解如何在 C++ 中使用 STL 反轉一個向量。
要反轉給定的向量,我們將使用 C++ 中 STL 庫中提供的 reverse() 函式。
示例
#include <bits/stdc++.h> using namespace std; int main(){ //collecting the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; cout << "Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; //reversing the vector reverse(a.begin(), a.end()); cout << "Reversed Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; return 0; }
輸出
Vector: 1 45 54 71 76 12 Reversed Vector: 12 76 71 54 45 1
廣告