0
点赞
收藏
分享

微信扫一扫

stl常用函数(积累中)

cnlinkchina 2022-03-11 阅读 58
算法

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 

 小疑问:1.[pos3-arr2.begin() ]为什么一定要减去初始位置迭代器才会返回下标值

 2.[pos1-arr] 为什么不减去初始位置返回地址值,减去初始位置返回下标值。

举报

相关推荐

stl常用函数

STL常用操作

STL常用算法

常用的STL

STL — 常用容器

STL常用容器

0 条评论