给定一个向量,请在C++中使用STL反转该向量。
例子:
Input: vec = {1, 45, 54, 71, 76, 12}
Output: {12, 76, 71, 54, 45, 1}
Input: vec = {1, 7, 5, 4, 6, 12}
Output: {12, 6, 4, 5, 7, 1}
方法:可以通过STL中提供的reverse()函数来完成反向操作。
句法:
reverse(start_index, last_index);
// C++ program to reverse Vector
// using reverse() in STL
#include
using namespace std;
int main()
{
// Get the vector
vector a = { 1, 45, 54, 71, 76, 12 };
// Print the vector
cout << "Vector: ";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << endl;
// Reverse the vector
reverse(a.begin(), a.end());
// Print the reversed vector
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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。