C++中lower_bound函数和upper_bound函数

时间:2022-09-28 17:56:39

转载自:http://blog.csdn.net/niushuai666/article/details/6734403

函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

举例如下:

一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标

pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。

pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。

pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。

所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~

返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置

 1 #include <iostream>
2 #include <algorithm>
3 #include <functional>
4 #include <vector>
5
6 using namespace std;
7
8
9 int main()
10 {
11 const int VECTOR_SIZE = 8 ;
12
13 // Define a template class vector of int
14 typedef vector<int > IntVector ;
15
16 //Define an iterator for template class vector of strings
17 typedef IntVector::iterator IntVectorIt ;
18
19 IntVector Numbers(VECTOR_SIZE) ;
20
21 IntVectorIt start, end, it, location ;
22
23 // Initialize vector Numbers
24 Numbers[0] = 4 ;
25 Numbers[1] = 10;
26 Numbers[2] = 11 ;
27 Numbers[3] = 30 ;
28 Numbers[4] = 69 ;
29 Numbers[5] = 70 ;
30 Numbers[6] = 96 ;
31 Numbers[7] = 100;
32
33 start = Numbers.begin() ; // location of first
34 // element of Numbers
35
36 end = Numbers.end() ; // one past the location
37 // last element of Numbers
38
39 // print content of Numbers
40 cout << "Numbers { " ;
41 for(it = start; it != end; it++)
42 cout << *it << " " ;
43 cout << " }\n" << endl ;
44
45 // return the first location at which 10 can be inserted
46 // in Numbers
47 location = lower_bound(start, end, 1) ;
48
49 cout << "First location element 10 can be inserted in Numbers is: "
50 << location - start<< endl ;
51 }