C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Addition of std::contains to Simplify Container Value Checks

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Sat, 23 Dec 2023 18:27:04 -0500
On Sat, Dec 23, 2023 at 5:21 PM Giuseppe D'Angelo via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Il 23/12/23 22:10, Sebastian Wittmeier via Std-Proposals ha scritto:
> > std::ranges::contains(range, value)
> > does exactly that:
> > - works over different container types
> > - provides a standardized way for checking for the presence of a value
> > So please state the advantages or differences of your proposal compared
> > to it.
>
> For starters, I'd like that if the container offers a `contains` method
> on its own (e.g. on std::set), then `std::whatever::contains` uses
> *that* one before falling back on linear search via std::(ranges::)find
> (not dissimilar to Python's protocol for `in`).
>

Reductio ad absurdum: We'd have to start by making
`std::ranges::find(myset, value)` optimize down to `myset.find(value)`. But
that's impossible, because `set::find` means "*set*, find the value (using
the equivalence relation induced by *your* comparator)" whereas
`ranges::find` means "*Ranges*, find the value (using `std::equal<void>`)."
Likewise, `set::contains
<https://en.cppreference.com/w/cpp/container/set/contains>` uses the set's
comparator rather than `std::less`.

So at the very least you'd have to figure out how to allow
`std::ranges::find(std::set<int>(), int)` and/or
`std::ranges::find(set<string_view, std::less<>>(), string)` to use
`set::find` while simultaneously forcing `std::ranges::find(set<Book,
ByAuthor>, Book)` to use linear search. This seems *very* hard to pin down,
even philosophically, before you even get to the standardese-wording part.

my $.02,
Arthur

Received on 2023-12-23 23:27:18