C++STL common operations of lower_bound, upper_bound articles

C++STL common operations of lower_bound, upper_bound articles

Introduction:

#include<algorithm>

lower_bound(start,last,key) returns the position of the first element greater than or equal to the target parameter

upper_bound(start,last,key) returns the position of the first element greater than the target parameter

They all have three parameters. The first parameter is the start position of the search interval, the second parameter is the last position after the end position of the search interval, and the third parameter is the target key value we need to find.

The search interval is an ordered interval with left closed and right open, as we can also see from the first and second parameters.

If it is not found, it returns last.

Binary search, the time complexity is O(logn).

use:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> v(5);
int main() {
    
    
	for (int i = 0; i < 5; ++i)
		cin >> v[i];
	cout << lower_bound(v.begin(), v.end(), 5) - v.begin() << endl;
    //输出第一个出现的大于5的位置
	cout << upper_bound(v.begin(), v.end(), 5) - v.begin() << endl;
    //输出第一个出现的大于5的位置
	cout << upper_bound(v.begin(), v.end(), 9) - v.begin() << endl;
    //未找到则输出last,这里是v.end()
	return 0;
}

Insert picture description here

We entered 2, 3, 5, 6, 8, and found the position of the first number greater than or equal to 5 in v is 2 (starting with 0, the same later), the first position greater than 5 is 3, all The numbers are less than or equal to 9, so the second upper_bound return value is the position after the end position of v (5).


If you find any problems, please correct me!

If you don’t understand, please leave a message!

Guess you like

Origin blog.csdn.net/qq_45985728/article/details/113054130