0%

c语言algorithm头文件下常用函数

algorithm头文件下常用函数

  1. max(),min(),abs()
    max(x,y)和min(x,y)分别返回x和y中的最大值和最小值,且参数必须是两个。
    abs(x) 返回x的绝对值。x必须为整数,浮点型的绝对值要用math头文件下的fabs

  2. swap()
    swap(x,y)用来交换x和y的值

  3. reverse()
    reverse(it,it2) 可以将数组指针在[it,it2)之间的元素或容器的迭代器在[it,it2)范围内的元素进行反转。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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;
}

#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;
}

sort()
默认为递增排序

  • 若要递减排序,需要增加比较函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bool cmp(int a,int b){
return a>b;
}
sort(a,a+n,cmp);
1
2
3
4
结构体数组排序
struct node{
int x,y;
}a[10];
bool cmp(node a,node b){
return a.x>b.x;
}
//
bool cmp(int x,int y){
if(a.x!=b.x) return a.x>b.x;
else return a.y<b.y;
}