algorithm用法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_41280600/article/details/102613870

五、#include < algorithm >

下面介绍的几个函数都作用在序列上,接收两个迭代器(或指针)l,r,对下标处于**前闭后开区间【l,r)**中的元素执行一系列操作。

  • sort() 快速排序

    int n = 3;
    int a[3] = {3,2,1};
    //对[0, n)区间进行排序 
    sort(a, a + n);
    

    可以在第三个参数传入定义大小比较的函数,或者重载“小于号“运算符。

    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    using namespace std; 
    struct node {
    	int d;
    	node(int dd) {
    		d = dd;
    	}
    	node(){}
    } a[100];
    
    bool cmp(node a, node b) {
    	//<符号是按照d小的排在前面
    	//retunr a.d > b.d是按照d大的排在前面 
    	return 	a.d < b.d;
    }
    int main() {
    	a[0] = node(3);
    	a[1] = node(2);
    	a[2] = node(1);
    	//【0, 3) 
    	sort(a, a + 3, cmp);
    	for (int i = 0; i < 3; i++) {
    		printf("%d ", a[i].d);
    	}
    	printf("\n");
    	return 0;
    }
    
  • reverse():翻转
    翻转一个vector: reverse(a.begin(), a.end());
    翻转一个数组: reverse(a, a + n) 下标是【0, n- 1】

  • lower_bound 二分查找
    lower_bound的第三个参数传入一个元素,在2个迭代器(或指针)指定的部分上执行二分查找,返回第一个大于等于x的元素的位置的迭代器。

    int a[5] = {0,1,2,3,4};
    //返回第一个大于等于2的元素的下标 
    int i = lower_bound(a, a + 5, 2) - a;
    
  • upper_bound

  • 用法与lower_bound大致相同,唯一的区别是查找第一个大于x的元素。当然2个指定的部分必须提前排好序

猜你喜欢

转载自blog.csdn.net/qq_41280600/article/details/102613870