Proposal: 'exists' in <algorithm>

74 views
Skip to first unread message

Marco Nef

unread,
Jun 14, 2017, 6:13:24 AM6/14/17
to ISO C++ Standard - Discussion
Reason

When someone just wants to check if an element exists in a container they have to write the following code:

if(std::find(begin(container), end(container), item) != end(container)) { ... }

There is always a duplication of end(container) which usually leads to very long lines and thus to less readable code than possible.


Solution

New function std::exists that returns a bool instead of an iterator:

template<class InputIt, class T>
InputIt exists(InputIt first, InputIt last, const T &value);

This function allows compacter Code, e.g. example under 'Reaseon':

if(std::exists(begin(container), end(container), item)) { ... }

The name exists can be exchanged by any other if there is a better naming. 

Richard Hodges

unread,
Jun 14, 2017, 6:19:55 AM6/14/17
to std-dis...@isocpp.org
Isn’t this simply:

if (std::one_of(begin(c), end(c), [&model](auto&&x) { return x == model; }))
{
  ...
}

Perhaps this argues for a std::equal_to<X>(X&& model) factory function that generates the appropriate unary function.

?

--

---
You received this message because you are subscribed to the Google Groups "ISO C++ Standard - Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to std-discussio...@isocpp.org.
To post to this group, send email to std-dis...@isocpp.org.
Visit this group at https://groups.google.com/a/isocpp.org/group/std-discussion/.

Marco Nef

unread,
Jun 14, 2017, 6:23:23 AM6/14/17
to ISO C++ Standard - Discussion
Am Mittwoch, 14. Juni 2017 12:19:55 UTC+2 schrieb Richard Hodges:
Isn’t this simply:

if (std::one_of(begin(c), end(c), [&model](auto&&x) { return x == model; }))
{
  ...
}


std::one_of does not exist, but you're right: it's std::any, right? 

Richard Hodges

unread,
Jun 14, 2017, 6:24:48 AM6/14/17
to std-dis...@isocpp.org
oops! You’re right.

I have however, often missed the presence of half-bound binary predicate


Marco Nef

unread,
Jun 14, 2017, 3:10:05 PM6/14/17
to ISO C++ Standard - Discussion
oops! You’re right.
 
Not quite, it's std::any_of ;-)
Reply all
Reply to author
Forward
0 new messages