vector<Widget> vw;
// populate vw
sort(vw.begin(), vw.end());
Widget w;
vector<Widget>::iterator i = lower_bound(vw.begin(), vw.end(), w);
if ( (i != vw.end()) && !(w < *i) ) // Yes, it is correct!
// found w in vw
Here is my understanding:
The return value of *i from lower_bound is always NOT less than that of w.
In other words, w <= *i
Here is the question, why not directly use the following condition for checking?
if ( (i != vw.end()) && (w == *i) ) // why not use (w == *i)?
// found w in vw
thank you
Because the implicit interface <algorithm>
uses for sorting and that kind of stuff only requires the <
operator to be defined on the data type. If they used ==
, they would force developers to implement it too on custom types to benefit from these functions.
In other words, if you make a sortable type Foo
, to use the functions defined in <algorithm>
, you only need to overload the <
operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With