实现翻转数组,字符串,向量!

1翻转数组

//头文件
#include <algorithm>
//使用方法
reverse(a, a+n);//n为数组中的元素个数

示例代码,

#include <iostream>
#include <algorithm>

using namespace std;

void MyShow(int a[], int n)
{
    for(int i = 0; i < n; i++)
        cout << a[i] << ' ';
    cout << endl;
}

int main()
{
    int a[5] = {1, 2, 3, 4, 5};
    //1 显示未翻转的数组内容
    MyShow(a, 5);
    //2 翻转数组然后再显示
    reverse(a, a+5);
    MyShow(a, 5);


    return 0;
}

输出为,

1 2 3 4 5
5 4 3 2 1

2翻转字符串

//用法为
reverse(str.begin(), str.end());

示例代码为,

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    string str = "abcdefg";
    //1 显示未翻转的字符串
    cout << str << endl;
    //2 翻转数组,然后显示
    reverse(str.begin(), str.end());
    cout << str << endl;


    return 0;
}

输出为,

abcdefg
gfedcba

3翻转向量

//用法
reverse(vec.begin(), vec.end());

示例代码为,

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void MyShow(vector<int> num)
{
    for(int i = 0; i < num.size(); i++)
        cout << num[i] << ' ';
    cout << endl;
}

int main()
{
    vector<int> vec = {1, 2, 3, 4, 5};

    //1 显示未翻转的向量
    MyShow(vec);
    //2 翻转数组然后再显示
    reverse(vec.begin(), vec.end());
    MyShow(vec);

    return 0;
}

输出为,

1 2 3 4 5
5 4 3 2 1
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐