Lower_bound implementation on vector pairs

I know that for this you need to enable some comparison function.

But he does not know how to write for this.

e.g. →

vector elements = {(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());

}
+4
source share
3 answers

Since you do not care about the second value pp, just create a temporary object ppwith any value as the second element.

int id = std::lower_bound(v.begin(), v.end(), pp(5, 0), cmp) - v.begin();
+4
source

( ) . - .

lower_bound, , val, , min , , "" :

sort(v.begin(),v.end());
auto id = distance(v.begin(), lower_bound(v.begin(),v.end(), 
       make_pair(5, numeric_limits<int>::min())) );

:

  • std::distance
  • std::distance . ( Python "count from the end" ), .
+3

I think you should compare the pairs as defined lower_bound so that

   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()
               );
+1
source

Source: https://habr.com/ru/post/1542837/


All Articles