C++ Logo

std-discussion

Advanced search

Re: contains() for iterable containers.

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 28 Aug 2023 16:18:58 -0400
On Mon, Aug 28, 2023 at 3:01 PM Ferhat Geçdoğan via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
> Currently, there's `std::find` to iterate over the containers to check the given element is in there or not. C++23 `std::basic_string` and `std::basic_string_view` comes with handy function, called `contains()` to check the substring is in there. Why would not the same functionality comes with `std::vector`, `std::array` or other iterable containers?
>
> Before, we would use that:
> `if(std::find(vec.begin(), vec.end(), item) != vec.end()) {}`
>
> With the power of `contains()`, we can use that:
> `if(vec.contains(item)) {}`

Because it wouldn't be the same function.

`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.

Received on 2023-08-28 20:19:11