如何使用C++中的STL反转向量
给定一个向量,使用C++中的STL来反转这个向量。
示例:
输入: vec = {1, 45, 54, 71, 76, 12}
输出: {12, 76, 71, 54, 45, 1}
输入: vec = {1, 7, 5, 4, 6, 12}
输出: {12, 6, 4, 5, 7, 1}
方法: 可以使用STL中提供的reverse()函数进行反转。reverse()的时间复杂度为O(n),其中n是字符串的长度。
语法:
reverse(start_index,last_index);
// C++程序,使用STL反转向量
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 获取向量
vector<int> a = { 1, 45, 54, 71, 76, 12 };
// 打印向量
cout << "向量:";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << endl;
// 反转向量
reverse(a.begin(), a.end());
// 打印反转的向量
cout << "反转后的向量:";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
输出:
向量:1 45 54 71 76 12
反转后的向量:12 76 71 54 45 1
时间复杂度:O(n),其中n是字符串的长度。