实现翻转数组,字符串,向量!
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