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