Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL - why use !(w < *i) rather than (w==*i)

Tags:

c++

stl

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

like image 548
q0987 Avatar asked Feb 24 '23 09:02

q0987


1 Answers

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.

like image 133
zneak Avatar answered Mar 07 '23 17:03

zneak