<algorithm>有哪些常用的函数

1.

max(x,y)求出两个数中的最大的数

min(x,y)求出两个数中的最小的数   

abs(x)求x的绝对值   类似于<cmath>中的fabs()函数

2.

reverse(begin,end)

将区间[begin,end)中的数逆序翻转

3.

sort(begin,end)

将区间[begin,end)中的数排序

若无cmp()函数,则默认为增序排序

扫描二维码关注公众号,回复: 9481093 查看本文章

若有cmp()函数,则按照cmp()函数的规则来进行排序

#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int x, y;
}ssd[10];
bool cmp(node a,node b)
{
return a.x > b.x; //按x值从大到小对结构体数组排序
}
int main()
{
ssd[0].x =2;ssd[0].y=2;
ssd[1].x =1;ssd[1].y=3;
ssd[2].x =3;ssd[2].y=1;
sort(ssd, ssd+3, cmp);//排序

for( int i=0; i<3; i++){
cout<< ssd[i].x <<endl;
}
cout<<" "<<endl;
return 0;
}

4.lower_bound(first,last,value)、upper_bound(first,last,value),他们都要在一个有序数组或有序容器中使用,lower_bound在[first,last)中找第一个值大于等于value的元素的位置,upper_bound在[first,last)中找第一个值大于value的元素的位置,所以返回的是数组的指针或者是容器的迭代器,当然只要减去了首地址得到的也就是目标元素的下标了。 时间复杂度均为:O(log(lastfirst))

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[10]={1,2,3,4,5,5,6,7,8,9};
int *lowerbound=lower_bound(a,a+10,5);
int *upperbound=upper_bound(a,a+10,5);
cout<<lowerbound-a<<endl;
cout<<upperbound-a<<endl;
return 0;
}

猜你喜欢

转载自www.cnblogs.com/pesuedream/p/11310231.html