STL built-in functions

lower_bound 与 upper_bound

  1. These two functions can sometimes replace our own handwritten dichotomy. We need to pass in three parameters, which are the start of the search interval, the next position at the end of the search interval, and the target value.
  2. Note that the search interval here is closed before opening, so the second parameter should be passed to the next position of the end

  3. Vector s is often used in conjunction with vector containers ;
    [s.begin(), s.end() ) is the query interval for all elements of s
  4. The function range value is an iterator (iterator) that needs to be represented by a value

code

#include<iostream>
#include<algorithm>//这是lower_bound 和 upper_bound函数所在的头文件
#include<cstring>

using namespace std;


int main(){
    
    
	int a[5] = {
    
    1, 2, 4, 5, 6};
	//不小于目标值的第一个,也就是说有和目标值相等的情况
	auto low = lower_bound(a, a + 5, 4);
	printf("%d\n", *low);
	//大于目标值的第一个,不存在和目标值相等的情况
	auto up = upper_bound(a, a + 5, 4);
	printf("%d\n", *up);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_63092029/article/details/129654848