简体   繁体   中英

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

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++ .

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 (ie 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.

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