C++ Logo

std-discussion

Advanced search

Re: contains() for iterable containers.

From: Giuseppe D'Angelo <giuseppe.dangelo_at_[hidden]>
Date: Tue, 29 Aug 2023 00:35:36 +0200
Il 28/08/23 22:18, Jason McKesson via Std-Discussion ha scritto:
>
> `string::contains` searches for a*substring*. Substrings are
> sequences of elements. `find` searches for a single element.
>
> It would be very confusing to have one container have a sub-sequence
> searching function named `contains` while another has an
> element-searching function named `contains`.
>
> Also, the difference between `ranges::find(vec, item)` and
> `vec.find(item)` is minimal.

But `contains()` on strings/string_views has also an overload for a
single element -- in general `str.contains(x)` is just equivalent to
`str.find(x) != npos`, including the case where `x` is a single
character. The ranges::contains algorithm also takes a single value to
look for.

The situation is already inconsistent, as the algorithm that searches
for subsequences in an arbitrary container is called std::search() (or
ranges::contains_subrange() for the "bool" answer), not contains().

One could argue that we need contains() on strings because
ranges::contains_subrange() is actually dangerous (think of
ranges::contains_subrange(haystack, "needle") -- doesn't do what one
expects!). On the other hand, there isn't much of a pressing reason for
having contains() as member function for ordinary containers.

>
> With the power of `contains()`, we can use that:
> `if(vec.contains(item)) {}`

This is spelled std::ranges::contains(vec, item), so it's just a bit
more verbose. The problem with this of course is discoverability, you
need to drown in the algorithmic pool to find out which one you need --
it's not on the "online help" for std::vector. I hope that the recent
additions on strings (starts_with, etc.), map::contains etc. are thawing
the ice in the "algorithm vs. member function" debate, and we could
sooner or later get some more convenience for all the containers...

My 2 c,
-- 
Giuseppe D'Angelo

Received on 2023-08-28 22:35:41