Boost logo

Boost :

From: Ivan Matek (libbooze_at_[hidden])
Date: 2022-04-06 00:15:52


On Mon, Apr 4, 2022 at 12:59 AM Marshall Clow via Boost <
boost_at_[hidden]> wrote:

>
> Why not just check to see if the returned iterator == end () ?
>
> Philosophical answer:
because find/find_if algorithm already knew that, he was just rude ;) and
did not give us back that information.
Practical answer:
I find writing !=.end spammy and potentially errorprone. I know it sounds
impossible to mess this up but in code that is not slideware mistakes can
happen. Also I prefer shorter code(when it comes to syntax spam, not
variable names) since for me it makes the logic more obvious.

Bonus :) answer:
Rust does it.
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find
Ben Deane used it in a talk:
https://www.youtube.com/watch?v=ojZbFIQSdl8&t=2138s

@Viktor I prefer to avoid pointers since they can be deleted and then bad
things can happen. But optional<T&> has similar functionality, it is just
harder to mistake for a something you need to delete... Also you can read
the Barry blog post on why he prefers optional<T&> over T*, here is picture
<https://brevzin.github.io/assets/optional-vs-ptr.png>he used to show they
are not really same....

@Andrey Semashev <andrey.semashev_at_[hidden]> I almost never do anything
with the iterator except comparing it to the end(). Again it is not that I
use find_if every day, but I use it a lot and I honestly do not remember
that I ever wanted to do something further with the iterator. Actually last
time I did something with iterators returned from algorithm it was a return
value of upper_bound, not find/find_if.

So IDK what else to say, I was really thinking this API is much better,
especially if Marshall would be interested in allowing container
overloads(on compilers with concepts) so code would look like:
    if (const auto maybe_val = ofind(v, x); maybe_val) {
      fmt::print("{}\n", *maybe_val);
    }

Beside fact that let or cauto would be much nicer than const auto I think
that code looks actually quite nice.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk