template <class ForwardIterator, class T> ForwardIterator lower_bound ( ForwardIterator first, ForwardIterator last, const T& value ); template <class ForwardIterator, class T, class Compare> ForwardIterator lower_bound ( ForwardIterator first, ForwardIterator last, const T& value, Compare comp ); | <algorithm> |
Return iterator to lower bound
Returns an iterator pointing to the first element in the sorted range [first,last) which does not compare less than value. The comparison is done using either operator< for the first version, or comp for the second.
For the function to yield the expected result, the elements in the range shall already be ordered according to the same criterion (operator< or comp).
Unlike upper_bound, this function returns an iterator to the element also if it compares equivalent to value and not only if it compares greater.
The behavior of this function template is equivalent to:
template <class ForwardIterator, class T> ForwardIterator lower_bound ( ForwardIterator first, ForwardIterator last, const T& value ) { ForwardIterator it; iterator_traits<ForwardIterator>::distance_type count, step; count = distance(first,last); while (count>0) { it = first; step=count/2; advance (it,step); if (*it<value) // or: if (comp(*it,value)), for the comp version { first=++it; count-=step+1; } else count=step; } return first; } |
Parameters
-
first, last
- Forward iterators to the initial and final positions of the sequence to use. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. value
- Element value to be checked for its lower bound. comp
- Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument goes before the second argument in the specific strict weak ordering it defines, and false otherwise.
Return value
Iterator to the lower bound position for value in the range.#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class student{
public:
int key;
int value;
/* bool operator()(student a,student b){
return a.key<b.key;
}*/
};
bool cmp(student a,student b){
return a.key<b.key;
}
int main(){
vector<student> vec(6);
int i;
vector<student>::iterator low;
vec[0].key=15;
vec[0].value=1;
vec[1].key=2;
vec[1].value=2;
vec[2].key=2;
vec[2].value=2;;
vec[3].key=3;
vec[3].value=3;
vec[4].key=3;
vec[4].value=4;
vec[5].key=7;
vec[5].value=5;
sort(vec.begin(),vec.end(),cmp);
for(i=0;i<6;i++)
cout<<vec[i].key<<endl;
low=lower_bound(vec.begin(),vec.end(),vec[3],cmp);
cout<<int(low-vec.begin())<<endl;
}