algorithm头文件下的常用函数

目录

max()、min()和abs()

swap()

reverse()

next_permutation()

fill()

sort()

如何使用sort()排序

如何实现比较函数cmp

容器的排序

lower_bound()和upper_bound()

max()、min()和abs()

max(x,y)和min(x,y)分别返回x和y中的最大值和最小值,且参数把叙事两个(可以是浮点数)。如果想要返回三个数x、y、z的最大值,可以使用max(x,max(y,z))的写法。

abs(x)返回x的绝对值。注意:x必须是整数,浮点型的绝对值使用math头文件下的fabs

#include<stdio.h>
#include<algorithm>
using namespace std;
int main(){
	int x=1,y=-2;
	printf("%d %d\n",max(x,y),min(x,y));
	printf("%d %d\n",abs(x),abs(y));
	return 0;
} 

swap()

swap(x,y)用来交换x和y的值

#include<stdio.h>
#include<algorithm>
using namespace std;
int main(){
	int x=1,y=-2;
	swap(x,y);
	printf("%d %d\n",x,y);
	return 0;
}

reverse()

reverse(it,it2)可以将数组指针在[it,it2)之间的元素或容器的迭代器在[it,it2)范围内的元素进行反转。

#include<stdio.h>
#include<algorithm>
using namespace std;
int main(){
	int a[10]={10,11,12,13,14,15};
	reverse(a,a+4);
	for(int i=0;i<6;i++){
		printf("%d ",a[i]);
	}
	return 0;
}

输出结果

13 12 11 10 14 15

如果是对容器中的元素(例如string字符串)进行反转,结果也是一样。

#include<stdio.h>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	string str="abcdefghi";
	reverse(str.begin()+2,str.begin()+6);
	for(int i=0;i<str.length();i++){
		printf("%c",str[i]);
	}
	return 0;
}

输出结果

abfedcghi

next_permutation()

next_permutation()给出一个序列在全排列中的下一个序列

例如,当n=3时的全排列为

123
132
213
231
312
321

这样231的下一个序列就是312

#include<stdio.h>
#include<algorithm>
using namespace std;
int main(){
	int a[10]={1,2,3};
	do{
		printf("%d%d%d\n",a[0],a[1],a[2]);
	}while(next_permutation(a,a+3));
	return 0;
}

输出结果

123
132
213
231
312
321

在上述代码中,使用循环是因为next_permutation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值