如何使用C++中的STL反转向量

如何使用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++
// 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;
}  
C++

输出:

向量:1 45 54 71 76 12 
反转后的向量:12 76 71 54 45 1
C++

时间复杂度:O(n),其中n是字符串的长度。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册