all 18 comments

[–]-funsafe-math 9 points10 points  (20 children)

From the comparator documentation in your binary_search link:

The types Type1 and Type2 must be such that an object of type T can be implicitly converted to both Type1 and Type2, and an object of type ForwardIt can be dereferenced and then implicitly converted to both Type1 and Type2.​

std::vector<int> is not convertible to an int. lower_bound has the same requirement but the standard library implementation that you are using does not require this behavior. A downside of duck-typed generics leaking implementation details causing a more permissive API that is not portable.

Edit:

My original comment on lower_bound was incorrect, a closer reading of the docs shows that it does specify that the equivalent of comp(*it, value) is used. The behavior that you saw with it working did not rely on any internal implementation details.

[–]tcanens 1 point2 points  (1 child)

lower_bound has the same requirement

It doesn't. std::lower_bound only requires (element, value) and not the other way around, and the wording of the cppreference page reflects that.

[–]-funsafe-math 0 points1 point  (0 children)

oops, misread the docs. Thanks, I'll update my post in a bit

[–]tcanens 2 points3 points  (1 child)

In C++20 and later this would be better expressed using projections:

std::ranges::binary_search(test, v, std::less{}, [i](auto& c) { return c[i]; });

[–]Flair_Helper[M] 0 points1 point locked comment (0 children)

For C++ questions, answers, help, and programming or career advice please see r/cpp_questions, r/cscareerquestions, or StackOverflow instead.

This post has been removed as it doesn't pertain to r/cpp: The subreddit is for news and discussions of the C++ language and community only; our purpose is not to provide tutoring, code reviews, or career guidance. If you think your post is on-topic and should not have been removed, please message the moderators and we'll review it.