algorithm头文件下的常用函数

algorithm头文件下的常用函数
1.max(),min(),abs()和swap()
使用实例:
#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));//max(),min()函数的用法 
	printf("%d %d\n",abs(x),abs(y));//abs()函数的用法
	swap(x,y);
	printf("%d %d\n",x,y);//swap()函数的用法
	return 0;
} 
运行结果:
1 -2
1 2
-2 1

2.reverse()
使用实例1:
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	int a[6]={10,8,9,11,2,9};
	reverse(a,a+4);//可以对任意区段进行逆序 
	for(int i;i<6;i++)
	{
		printf("%d ",a[i]);
	}
	return 0;
} 
运行结果:
11 9 8 10 2 9
使用实例2:如果对容器中的元素(例如string字符串)进行反转,结果也是一样
#include<stdio.h>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
	string str="askgdkafckah";
	reverse(str.begin(),str.end());
	for(int i=0;i<str.length();i++)
	{
		printf("%c",str[i]);
	}
	return 0;
}
运行结果:
hakcfakdgksa

3.next_permutation()
next_permutation()给出一个序列在全排列中的下一个序列
下面是一个实现1,2,3,4全排列的例子:
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	int a[4]={1,2,3,4};
	do{
		printf("%d%d%d%d\n",a[0],a[1],a[2],a[3]);
	}while(next_permutation(a,a+4));
	return 0;	
 } 
运行结果:
1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321

4.fill()
fill()可以把数组或容器中的某一段区间赋为某个相同的值。和memset不同,这里的赋值可以是数组类型对应范围中的任意值。示例如下:
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	int a[5]={1,2,3,4,5};
	fill(a,a+5,666);
	for(int i;i<5;i++)
	{
		printf("%d ",a[i]);
	}
	return 0;
 } 
运行结果:
666 666 666 666 666

5.lower_bound()和upper_bound()
lower_bound()和upper_bound()都是用在有序数组或容器中,lower_bound()是返回第一个大于或等于要查找的数,upper_bound()则是返回第一个大于要查找的数
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	int a[10]={1,2,2,3,3,3,4,4,4,4};
	int *lowerPos=lower_bound(a,a+10,3);
	int *upperPos=upper_bound(a,a+10,3);
	printf("%d,%d\n",lowerPos-a,upperPos-a);
	return 0; 
}
运行结果:
3,6





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值