STL & lower_bound 、 upper_bound、binary_search

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



lower_bound(起始地址,结束地址,要查找的数值val) 返回容器中第一个值【大于或等于】val的元素的iterator位置,通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

lower_bound( begin,end,val,greater<type>() ) 返回容器中第一个值第一个【小于或等于】val的元素的iterator位置


upper_bound(起始地址,结束地址,要查找的数值val) 返回容器中第一个值【大于】val的元素的iterator位置,通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

upper_bound( begin,end,val,greater<type>() ) 返回容器中第一个值第一个【小于】val的元素的iterator位置


binary_search(起始地址,结束地址,要查找的数值val) 返回的是是否存在这么一个数,是一个bool值。


void test02(){
	vector<int> vec = { 1, 3, 5, 7, 9, 11 };
	//lower_bound
	//1.求迭代器
	auto iter1 = lower_bound(vec.begin(), vec.end(), 3); //指向3
	//2.求下标
	int pos1 = lower_bound(vec.begin(), vec.end(), 3) - vec.begin(); //下标 = 查找到的迭代器-vec.begin()
	//upper_bound
	//1.求迭代器
	auto iter2 = upper_bound(vec.begin(), vec.end(), 3); //指向5
	//2.求下标
	int pos2 = upper_bound(vec.begin(), vec.end(), 3) - vec.begin(); //下标 = 查找到的迭代器-vec.begin()
}
#include<bits/stdc++.h>
using namespace std;
const int maxn=100000+10;
const int INF=2*int(1e9)+10;
#define LL long long

int cmd(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;    //返回数组中第一个大于或等于被查数的值 
    int pos2=upper_bound(num,num+6,7)-num;    //返回数组中第一个大于被查数的值
    
    sort(num,num+6,cmd);                      //按从大到小排序
    int pos3=lower_bound(num,num+6,7,greater<int>())-num;  //返回数组中第一个小于或等于被查数的值 
    int pos4=upper_bound(num,num+6,7,greater<int>())-num;  //返回数组中第一个小于被查数的值 
}

猜你喜欢

转载自blog.csdn.net/weixin_36750623/article/details/92074335