C++ STL的使用
标签: C++ STL的使用
学习人数: 29.4k


高清播放
赞赏支持

C++的算法头文件里有很多很实用的函数,我们可以直接拿来用。

#include <algorithm>

 

排序

sort()函数:依次传入三个参数,要排序区间的起点,要排序区间的终点+1,比较函数。比较函数可以不填,则默认为从小到大排序。

使用示例

#include <bits/stdc++.h>  
using namespace std;  
  
int a[105];  
int main() {  
    int n;  
    scanf("%d", &n);  
    for (int i = 0; i < n; i++) {  
        scanf("%d", &a[i]);  
    }  
    sort(a, a+n);  
    for (int i = 0; i < n; i++)  
        printf("%d ", a[i]);  
    return 0;  
}  

 

 

查找

lower_bound()函数
upper_bound()函数
lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。

 

在从小到大的排序数组中,
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

在从大到小的排序数组中,重载lower_bound()和upper_bound()
lower_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

使用示例

#include<bits/stdc++.h>  
using namespace std;  
  
int cmp(int a,int b){  
    return a>b;  
}  
int main(){  
    int num[6]={1,2,4,7,15,34};  
    sort(num,num+6);  //按从小到大排序  
    int pos1=lower_bound(num,num+6,7)-num;      
    //返回数组中第一个大...
登录查看完整内容


课后作业

掌握C++ STL的使用


登录后开始许愿

3 条上岸许愿
Zyc_nj
2024年1月3日 11:09

1

赞(0)
bit8421
2021年1月6日 19:04

map,红黑树,log。set,去重。

赞(0)
bit8421
2021年1月6日 14:47

sort()复杂度可视为O(nlogn)

赞(0)