On 2/11/2019 04:34, Zach Laine wrote:
This is a red herring; if you only care about existence, why are you using find()? Use any_of() or C++20's includes() (for detecting subranges) instead. They each return a bool. Moreover, just knowing whether a value is found at all within a subrange via linear search is a corner case -- usually you will use something with O(log(N)) or faster access if you need to do that operation a lot.
I'm using find because you said to use find. :) But yes, the argument applies to map.find and friends as well -- and would probably be more useful there than for std::find itself. "Is key present in map" is a very common query. (Granted, map.contains has been added in C++20, but most people don't have access to that yet.)
If I had to write that code using your approach, it would suffer. All I'm pointing out here is that the change you propose is not universally better. In fact, it is universally worse if what you want to do is search for a subrange:
auto lower = std::lower_bound(c.begin(), c.end(), 42); out = std::copy(lower, std::upper_bound(lower, c.end(), 42), out);
Or:
out = std::ranges::copy(std::ranges::equal_range(c, 42), out);
That turns in to a real mess when the iterators returned are optionals.
I don't really like the former example anyway because you're not checking for failure of lower_bound. Granted, it will end up with an empty range in the end so the result will still be correct, but you're potentially wasting some time in upper_bound. In the second example it would return an empty range either way, so there's not really any difference.