Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the predicate version of lower_bound and upper_bound passing the iterator value inconsistently?

Tags:

c++

algorithm

stl

In upper_bound's binary predicate, the iterator value is passed as the second argument while in lower_bound the iterator value is passed as the first argument.

What is the reasoning here? And does it matter if I remember this detail or not when writing my own binary predicates?


NOTE my reference is www.cplusplus.com (which I am told may not be the best reference) and I confirmed it by looking at the implementation in the stl library shipped with VC++.

like image 604
Samaursa Avatar asked Oct 28 '25 06:10

Samaursa


1 Answers

This is intentional. The reasoning is so you can use the same comparator for both algorithms. Consider the descriptions. lower_bound:

Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value.

and upper_bound:

Returns an iterator pointing to the first element in the range [first, last) that is greater than value.

Consider that the standard comparator is <. In order to implement both algorithms with only < would require !(elem < value) for one and value < elem for the other. The inversion of the order of arguments just follows directly from that.

This shouldn't affect how you implement your Comparator though.

like image 52
Barry Avatar answered Oct 29 '25 21:10

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!