algorithm头文件下的常用函数-学习笔记
#include < algorithm >
using namespace std;
max(x,y),min(x,y),abs(x)
max和min返回x和y中的最大值和最小值,参数可以是浮点数。如果要返回三个数的最值,可以使用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=-5;
printf("%d %d\n",max(x,y),min(x,y));
printf("%d %d\n",abs(x),abs(y));
return 0;
}
swap(x,y)
交换x和y的值。
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
int x=1,y=-5;
swap(x,y);
printf("%d %d\n",x,y);
return 0;
}
reverse(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); //将a[0]~a[3]反转
for(int i=0;i<6;i++){
printf("%d ",a[i]);
}
return 0;
}
对容器中的元素进行反转:
#include <stdio.h>
#include <algorithm>
#include <string>
using namespace std;
int main(){
string str="abcdefg";
reverse(str.begin()+2,str.begin()+6); //c d e f
for(int i=0;i<str.length