reverse()函数用来翻转数组,字符串,向量;
头文件:#include<algorithm>
1.翻转字符串
reverse(s.begin(),s.end()); //翻转整个字符串
reverse(s.begin()+i,s.begin()+k); //翻转下标i到k(不包含k)
示例:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
string s = "abcdefg";
string c = "hijklmn";
reverse(s.begin(), s.end());//翻转整个字符串
reverse(c.begin() + 2,c.begin() + 5);//翻转下标2到5(不包括5)
cout << s << endl;
cout << c;
return 0;
}
输出:
gfedcba
hilkjmn
2.翻转数组
reverse(a,a+n);//n为数组长度 翻转整个数组
reverse(a+i,a+k);//翻转指定范围 下标为i到k(不包括k)
示例:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int s[5] = { 1,2,3,4,5 };
int a[5] = { 1,2,3,4,5 };
reverse(s, s + 5); //翻转整个数组
reverse(a + 2, a + 4); //翻转指定范围 下标2到4(不包括4)
for (int i = 0; i < 5; i++)
{
cout << s[i] << " ";
}
cout << endl;
for (int j = 0; j < 5; j++)
{
cout << a[j] << " ";
}
return 0;
}
输出:
5 4 3 2 1
1 2 4 3 5
3.翻转vector
reverse(vect.begin(),vect.end());//写法和数组一样