C++ reverse()函数 详解

本文详细介绍了C++标准库中的reverse()函数使用方法,包括如何翻转字符串、数组及vector容器,并提供了丰富的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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());//写法和数组一样

 

可参考例题:541. 反转字符串 II - 力扣(LeetCode)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值