On 4/04/2022 10:58, Marshall Clow wrote:
On Apr 3, 2022, at 3:09 PM, Viktor Sehr wrote:
Why not return a pointer/nullptr instead? pfind_if
Why not just check to see if the returned iterator == end () ?
The annoyance with the iterator == end() implementation is that it's a double indirection -- if you want to access the value afterwards it has to be in a separate statement, which means you can't do it with an rvalue collection. The same applies with a pointer-find; it's still a non-owning indirection that's invalid on rvalue collections. The optional return doesn't have that problem; because it copies the value, the value remains valid when returned from an rvalue collection. Granted, rvalue collections can be inefficient in themselves (since it means you're recalculating some collection instead of caching it), but simply making the code unsafe unless you assign the collection to a variable doesn't actually help eliminate that usage, it just makes it wordier. And with the rise of ranges and collection filters/views (which tend to be light rvalues), that sort of coding style will become more common, not less. At the end of the day, which usage makes more sense depends on how you're interacting with the collection -- do you only care about reading the value, or do you need to modify/remove the value? Do you need the value itself or do you only care if it's in there? Is the value cheap to copy? The stdlib interface is deliberately minimal (and rightly so) -- it does *let* you do everything, but it's not the most friendly. (I usually end up making set::contains and map::get helper methods to improve code conciseness and readability; these are the most common "missing" operations.)