目录
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