Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of lower_bound on vector pairs

I know we need to include some compare function in order to achieve this.

But not able to write for this one.

For example:

Elements of vector={(2,4),(4,2),(5,1),(5,3)}

to find=5

lower_bound() should return 2

code->

#define pp pair<int,int>

bool cmp(const pp &l,const pp &r) {
    return l.first < r.first;
}

int main() {
   vector<pp> v;
   sort(v.begin(), v.end(), cmp);
   int id=(int)(lower_bound(v.begin(), v.end(), ??) - v.begin());
}
like image 593
user2826957 Avatar asked Jun 01 '14 15:06

user2826957


1 Answers

I think you should compare the pairs as per definition of lower_bound So,

   typedef pair<int,int> pp;
   //...

   int id=(int)(lower_bound(v.begin(),v.end(), 
                pp(5,std::numeric_limits<int>::min())), //Value to compare
                [](const pp& lhs, const pp& rhs)       // Lambda
                {
                    return lhs < rhs ;                //  first argument < second
                }
                 ) - v.begin()
               );
like image 103
P0W Avatar answered Oct 16 '22 17:10

P0W