stl提供的应用二分查找的函数:
#include<algorithm>
lower_bound(first,end,val) 函数(前提是指定的范围必须有序)
用于在指定区域内查找第一个不小于目标值元素的位置。也就是说,使用该函数在指定范围内查找某个目标值时,最终查找到的不一定是和目标值相等的元素,还可能是比目标值大的元素.
其中,first 和 last 都为正向迭代器,[first, last) 为函数的作用范围;val 为目标元素。
返回值为 指向第一个不小于目标值元素迭代器,若找不到则返回last迭代器。
int arr[8]={4,10,11,30,69,78,96,100};
int *pos1=lower_bound(arr,arr+8,68);
cout<<pos1-arr<<" "<<*pos1<<endl;
//返回 4 69
int *pos2=lower_bound(arr,arr+8,78);
cout<<pos2-arr<<" "<<*pos2<<endl;
//返回5 78
vector<int> arr2 = {100,96,78,69,30,11,10,4};//给定数值就不需要指定vector的大小
vector<int>::iterator pos3=lower_bound(arr2.begin(),arr2.end(),78,greater<int>());
cout<<pos3-arr2.begin()<<" "<<*pos3<<endl;
//返回 5 78
若指定的范围是降序的,则须使用lower_bound(first,end,val,comp),comp用于自定义比较规则,也可以直接用greater<int>()代替。
小疑问:1.[pos3-arr2.begin() ]为什么一定要减去初始位置迭代器才会返回下标值
2.[pos1-arr] 为什么不减去初始位置返回地址值,减去初始位置返回下标值。
—— —— —— —— —— —— —— —— —— —— — —— —— —— —— —— —— —— ——
sort():(不稳定排序,排序会改变元素初始位置)
sort(a+1,a+n+1)对数组1~n升序排序
sort(a+1,a+n+1,greater<int>())对数组1~n降序排序(与priority_queue()那个正好相反)
升序队列,小顶堆 priority_queue <int,vector<int>,greater<int> > q; 降序队列,大顶堆 priority_queue <int,vector<int>,less<int> >q;(默认是大顶堆)
重载运算符(用于排序结构体)
struct node{
int l,r;
bool operator<(const node b)const{
return l<b.l;//按l升序
}
};
———————————————————————————————————————————
find():查找相同元素,逐一比较
C++ find()函数用法详解(超级详细) (biancheng.net)http://c.biancheng.net/view/7489.html