使用algorithm头文件,需要在头文件下面加一行using namespace std;
1.max(),min()和abs()
max(x,y)和min(x,y)分别返回x和y中最大值和最小值,而且参数必须是两个(可以是浮点数)。如果想要返回三个数x,y,z的最大值,可以使用max(x,max(y,z))的写法。
abs(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;
}
输出结果:
1 -2
1 2
2.swap()
swap(x,y)用来交换x,y的值,示例如下
#include <stdio.h>
#include <algorithm>
int main(){
int x = 1,y=2;
swap(x,y);
printf("%d %d",x,y);
return 0;
}
输出结果:
2 1
经过自己摸索,我还发现了数组也可以用这种方法交换,平时就不用再单独写个swap函数了,非常方便。示例如下:
#include<bits/stdc++.h>
using namespace std;
int main(){
int a[2] = {1,2};
swap(a[0],a[1]);
printf("%d %d",a[0],a[1]);
}
输出结果:
2 1
3.revers()
revers(it,it2)可以将数组指针在[it,it2)之间的元素或容器的迭代器在[it,it2)范围内的元素进行反转。示例如下:
#include<cstdio>
#include<algorithm>
int main(){
int a[10] = {10,11,12,13,14,15};
reverse(a,a+4);//将a[0]~a[3]反转
for(int i=0;i<6;i++){
printf("%d ",a[i]);
}
return 0;
}
输出结果:
13 12 11 10 14 15
如果是对容器中的元素(例如string字符串)进行反转,结果也是一样的:
#include <cstdio>
#include <string>
#include <algortithm>
int main(){
string str = "abcdefghi";
reverse(str.begin()+2,str.begin()+6);//对str[2]~str[5]反转
for(int i = 0 ; i<str.length();i++){
printf("%c",str[i]);
}
return 0;
}
输出结果:
abfedcghi
4.next_permutation()
next_permutation()给出一个序列在全排列中的下一个序列
例如,当n == 3时的全排列为:
123
132
213
231
312
321
这样231的下一个序列就是312.
示例如下
#include <cstdio>
#include <algorithm>
int main(){
int a[10] = {1,2,3};
//a[0]~a[2]之间的序列需要求解next_permutation
do{
printf("%d%d%d",a[0],a[1],a[2]);
}while(next_permutation(a,a+3));
return 0;
}
输出结果:
123
132
213
231
312
321
在上述代码中,使用循环是因为next_permutation在已经到达全排列的最后一个时会返回false,这样会方便退出循环。而使用do…while语句而不使用while语句是因为序列1 2 3本身也需要输出,如果使用while会直接跳到下一个序列再输出,这样结果会少一个123。
5.fill()
fill()可以把数组或容器中的某一段区间赋值为某个相同的值。和memset不同,这里的赋值可以是数组类型对应范围中的任意值。示例如下:
#include <cstdio>
#include <algorithm>
using namespace std;
int main(){
int a[5] = {1,2,3,4,5};
fill(a,a+5,233);//将a[0]~a[4]均赋值为233
for(int i =0;i<5;i++){
printf("%d",a[i]);
}
return 0;
}
输出结果:
233 233 233 233 233
6.sort()
sort()可以说是最有意思,也是algorithm里面最好刷题偷塔节省代码量的一个宝藏函数啦~~要单独给sort()写一篇。过两天更新。