C++ Logo


Advanced search

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

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Sat, 23 Dec 2023 09:54:11 +0000
On Sat, 23 Dec 2023, 09:21 Robert Sitton via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> Dear std-proposals community,
> I hope this email finds you well. I am writing to introduce a proposal for
> the addition of a new utility function, std::contains, to the C++ standard
> library. This function aims to streamline the common task of checking
> whether a container contains a specific element and enhance the overall
> readability of C++ code.
> Motivation:
> One of the frequent operations in C++ programming involves checking
> whether a container (e.g., std::vector, std::list, std::set) contains a
> particular value. While C++ provides mechanisms to achieve this, such as
> custom loops or std::find, these approaches may not always be as intuitive
> and efficient as desired.
> Proposal Overview:
> The proposed std::contains function is designed to simplify this operation
> and make code more expressive. It offers a straightforward and concise way
> to check if a container contains a specified element, reducing the need for
> manual iterations and enhancing code clarity.
> Function Signature:
> template <typename Container, typename T>
> bool std::contains(const Container& container, const T& value);
> Example Usage:
> std::vector<int> numbers = {1, 2, 3, 4, 5};
> bool containsThree = std::contains(numbers, 3); // true
> bool containsTen = std::contains(numbers, 10); // false
> bool containsOne = std::contains(numbers, {1, 4, 5}); // true
> bool containsTwo = std::contains(numbers, {7, 8}); // false
> Your Feedback:
> I would greatly appreciate your feedback and insights on this proposal.
> Before formally submitting it to the C++ committee, I believe it is
> essential to gather input from the community to ensure that the proposal
> aligns with the needs and expectations of C++ developers.
> Please feel free to share your thoughts, suggestions, or concerns
> regarding the proposed std::contains function. Your expertise and feedback
> are invaluable in refining and improving this idea. Thank you for your time
> and attention. I look forward to engaging in constructive discussions and
> working together to enhance the C++ standard library.

We already have std::string::contains but that searches for a single
element _or_ a substring. Should that also be possible here? A subsequence
doesn't even make sense for unordered containers, but could be useful as a
simpler form of std::search for other containers.

I'm not convinced it's needed, but your proposal should discuss it either
way, I think.

Received on 2023-12-23 09:54:27