算法笔记(15)| algorithm

2019-08-27  本文已影响0人  yzbkaka

在使用algorithm库时,必须要添加using namespace std才可以使用。

1.max()、min()和abs()

max(x,y)和min(x,y)返回x、y中最大的数和最小的数,而且参数必须是两个。如果想要比较三个数之间的大小,则可以使用max(x,max(y,z))或min(x,min(y,z))。

abs()是返回整数x的绝对值,如果是要求浮点数的绝对值,则可以使用#include<math.h>下的fabs()函数。

2.swap()

swap(x,y)函数主要是用来交换x和y的值。

3.reverse()

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

#include<stdio.h>
#include<algorithm>
using namespace std;
int main(){
    int a[10] = {1,2,3,4,5};
    reverse(a,a+4);  //反转a[0]到a[3]
    for(int i=0;i<5;i++){
        printf("%d ",a[i]);
    } 
    return 0;
} 

//输出结果:4 3 2 1 5

需要注意的是,reverse()对于容器类型的反转和数组之间的反转是类似的。

4.next_permutation()

next_permutation()给出一个序列在全排列中的下一个序列。

#include<stdio.h>
#include<algorithm>
using namespace std;
int main(){
    int a[3] = {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

5.lower_bound()和upper_bound()

lower_boune(first,last,val)是用来寻找数组或容器的[first,last)范围内第一个值大于等于val的元素的位置,如果是数组,则返回该元素位置的指针;如果是容器,则返回该元素位置的迭代器。

upper_bound(first,last,val)是用来寻找数组或容器的[first,last)范围内第一个值大于val的元素的位置,如果是数组,则返回该元素位置的指针;如果是容器,则返回该元素位置的迭代器。

#include<stdio.h>
#include<algorithm>
using namespace std;
int main(){
    int a[10] = {1,2,2,3,3,3,5,5,5};
    int* lowerPos;
    int* upperPos;
    //寻找-1
    lowerPos = lower_bound(a,a+10,-1);
    upperPos = upper_bound(a,a+10,-1);
    printf("%d %d\n",lowerPos-a,upperPos-a);  //输出下标 
    //寻找1
    lowerPos = lower_bound(a,a+10,1);
    upperPos = upper_bound(a,a+10,1);
    printf("%d %d\n",lowerPos-a,upperPos-a);
    return 0;
} 

输出结果:
0 0
0 1
上一篇 下一篇

猜你喜欢

热点阅读