std::find_if takes a predicate in one of it’s overloaded function. Binders make it possible to write EqualityComparators for user-defined types and use them either for dynamic comparison or static comparison.
In contrast the binary search functions of the standard library take a comparator and a const T& to the value that should be used for comparison. This feels inconsistent to me and could possibly more inefficient as the comparator has to be called with both arguments every time instead of having the constant argument bound to it. While it could be possible to implement std::binary_search in a way to use std::bind this would require all comparators to inherit from std::binary_function. Most code I’ve seen doesn’t do that.
Is there a possible benefit from letting comparators inherit from std::binary_function when using it with algorithms that take a const T& as a value instead of letting me use the binders? Is there a reason for not providing predicate overloads in those functions?
A single-argument predicate version of
std::binary_searchwouldn’t be able to complete in O(log n) time.Consider the old game “guess the letter I’m thinking of”. You could ask: “Is it A?” “Is it B?”.. and so on until you reached the letter. That’s a linear, or O(n), algorithm. But smarter would be to ask “Is it before M?” “Is it before G?” “Is it before I?” and so on until you get to the letter in question. That’s a logarithmic, or O(log n), algorithm.
This is what
std::binary_searchdoes, and to do this in needs to be able to distinguish three conditions:A one-argument predicate P(x) says only “x has property P” or “x doesn’t have property P”. You can’t get three results from this boolean function.
A comparator (say,
<) lets you get three results by calculating C < X and also X < C. Then you have three possibilities:!(C < X) && !(X < C)C is equal to XC < X && !(X < C)C is less than X!(C < X) && X < CC is greater than XNote that both X and C get bound to both parameters of
<at different times, which is why you can’t just bind X to one argument of<and use that.Edit: thanks to jpalecek for reminding me binary_search uses <, not <=.
Edit edit: thanks to Rob Kennedy for clarification.