【STL】STL之lower_bound与upper_bound
来源:互联网 发布:cf手游刷枪软件注册码 编辑:程序博客网 时间:2024/06/05 11:41
这两个函数都用于二分查找。当然,必须要先进行升序排序。
一.lower_bound
lower_bound用于查找某个元素第一个不小于它的元素地址。
lower_bound(begin,end,a)在[begin,end)中查找第一个不小于a的元素地址。
例如:
1 1 2 2 3 5 6 (下标从1开始)
lower_bound(1)返回位置为1
lower_bound(4)返回位置为6
lower_bound(7)返回位置为8 注意此时已经越界了!!!
#include <iostream>#include <cstdio>#include <algorithm>#define MAXN 1005using namespace std;int n ,num[MAXN] ;int a ;int main(){ scanf("%d",&n); for(int i=0;i<n;++i) scanf("%d",&num[i]); sort(num,num+n); scanf("%d",&a); printf("%d\n",lower_bound(num,num+n,a)-num); return 0;}
二.upper_bound
同lower_bound,upper_bound用法一样,只是它是返回第一个大于a的元素地址。
例如:
1 1 2 2 3 5 6 (下标从1开始)
upper_bound(1)返回位置为3
upper_bound(4)返回位置为6
upper_bound(7)返回位置为8 注意此时已经越界了!!!
#include <iostream>#include <cstdio>#include <algorithm>#define MAXN 1005using namespace std;int n ,num[MAXN] ;int a ;int main(){ scanf("%d",&n); for(int i=0;i<n;++i) scanf("%d",&num[i]); sort(num,num+n); scanf("%d",&a); printf("%d\n",upper_bound(num,num+n,a)-num); return 0;}
三.unique
这个函数用于去重排序,蒟蒻认为比较有用。
在使用之前必须要排序(即sort一下)
unique(begin,end)对[begin,end)之间去重,并返回结束的地址。
#include <iostream>#include <cstdio>#include <algorithm>#define MAXN 1005using namespace std;int n ,num[MAXN] ;int main(){ scanf("%d",&n); for(int i=0;i<n;++i) scanf("%d",&num[i]); sort(num,num+n); int end=unique(num,num+n)-num; printf("%d\n",end); for(int i=0;i<end;++i) printf("%d ",num[i]); return 0;}
0 0
- 【STL】STL之lower_bound与upper_bound
- STL lower_bound与upper_bound
- stl函数之lower_bound 与 upper_bound
- Lower_bound与Upper_bound (STL)
- STL之lower_bound()、upper_bound()、binary_search
- STL函数之lower_bound upper_bound
- stl lower_bound 和 upper_bound
- C++ STL lower_bound upper_bound
- C++ STL lower_bound & upper_bound
- STL lower_bound和upper_bound
- [STL] lower_bound和upper_bound
- lower_bound/upper_bound(STL)
- STL函数 lower_bound / upper_bound
- C++ STL lower_bound & upper_bound
- STL 二分法 upper_bound()与lower_bound()使用方法
- STL中的二分查找,lower_bound();与upper_bound();
- 浅谈STL中的二分lower_bound()与upper_bound()
- C++ STL 之 lower_bound and upper_bound
- windos上修改mysql编码!
- 音乐(多媒体)SoundPool,MediaRecorder和Mediaplayer
- OBJC_ASSOCIATION 关联学习
- 改变用户默认shell
- android studio 分享文件到github
- 【STL】STL之lower_bound与upper_bound
- 手动释放linux内存cache
- hdu5443The Water Problem 并查集
- Android多媒体---Camera(调用系统Camera,非自定义)
- Fizz Buzz
- 输入输出之InputStream&OutputStream、Reader&Writer
- 关键字const总结
- Adaboost特征值计算
- iOS学习 bounds