Lower_bound (begin, end, target) is used to find an element in a sorted sequence [begin, end] the first one greater than or equal to target. The array A is as follows:
Value:1, 2, 2, 3, 4, 5, 5, 6, 7
index:0, 1, 2, 3, 4, 5, 6, 7, 8
Such a sequence, if looking for 5 lower_bound, should return the first 5 that is a[5]. The following is an excerpt from the Lower_bound code on cplusplus.com
Template <classForwardIterator,classT>ForwardIterator Lower_bound (forwarditerator first, ForwardIterator last,Constt&val) {ForwardIterator it; Iterator_traits<ForwardIterator>::d ifference_type count, step; Count=distance (first,last); while(count>0) {It= First; step=count/2; advance (it,step); if(*it < Val) {//or:if (Comp (*it,val)), for version (2)First = + +it; Count-= step+1; } ElseCount =step; } returnFirst ;}
If the search object is just an array, you can simplify it a little bit:
Count = last- start; while 0 ) { = count/2; int* it = first + step; if (*it < target) { 1); 1 ; Else { Count=step; }} return first;
Basic: Returns end when the input has only one element, which is not the element to find, that is, the next position of the element
When looking for a 4 lower_bound in an array, the first *it value is 4, because this is not a simple binary search, but instead returns the position of the first greater than or equal to the lookup element, so the search cannot end at this time. However, you can be sure that this section of 5~7 is not searchable because at least one element at the moment is *it is greater than or equal to 4, thus narrowing the lookup range (count=step). This lookup does not include the 4 that has been found, why is this? Sub-situation discussion:
1. When the previous range does not match the number of conditions, the last position of the final position of the range is returned, and this position is exactly where the 4 is located, that is, the location of the *it>= target when it is located, which matches the search criteria.
2. When the front of this position contains the number of eligible, at this time the current 4 is not lower_bound, also do not have to consider
C + + Stl:lower_bound implementation