简体   繁体   中英

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());
}

Pairs ( just like tuples ) compare lexicographically anyway. You don't need to define any special comparators for this.

And since you're using lower_bound you'll be searching for the first element that does not compare less than the val you're searching, so you should use a min value as the second pair element. To sum up, all can be done in "two" lines of code :

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

Some Notes :

  1. Use std::distance to calculate the number of elements between two iterators
  2. The return type of std::distance is an unsigned type. Unless you need negative indexing (Python like syntax for "count from the end" indexes) it's a good practice to keep your indexes unsigned.

由于您不关心pp的第二个值,因此只需构造一个具有任何值作为第二个元素的临时pp对象。

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

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()
               );

You can use lower_bound on vector of pairs with custom compare operator .

You need to pass four arguments in that case like this :-

  • it1 = iterator position from where to search

  • it2 = iterator position till where to search

lower_bound (it1 ,it2 , finding_element, your_comparator )

auto myComp = [&](pair<int,string> e1, pair<int,string> e2) {
if(e1.second!=e2.second)
    return e1.second<e2.second;
else
    return e1.first<e2.first;
};
 
void Show_sample_code()
{
    vector<pair<int,string>> data={{1, "sahil"}, {2, "amin"}};
    sort(data.begin(), data.end(), myComp);
    pair<int, string> p={1,"sahil"};
    auto it=lower_bound( data.begin(), data.end(), p, myComp ) ;
    if(it!=data.end())
         cout<<"found at index="<<distance(data.begin(), it)<<endl;
    else
    cout<<"notfound"<<endl;
return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM