Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What STL algorithm can determine if exactly one item in a container satisfies a predicate?

I need an STL algorithm that takes a predicate and a collection and returns true if one and only one member of the collection satisfies the predicate, otherwise returns false.

How would I do this using STL algorithms?

E.g., to replace the following with STL algorithm code to express the same return value.

int count = 0;  for( auto itr = c.begin(); itr != c.end(); ++itr ) {     if ( predicate( *itr ) ) {       if ( ++count > 1 ) {         break;       }     } }  return 1 == count; 
like image 827
WilliamKF Avatar asked Jun 07 '19 20:06

WilliamKF


People also ask

What does STL find do when the element is not in the container?

set find() function in C++ STL The set::find is a built-in function in C++ STL which returns an iterator to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.


1 Answers

Two things come to my mind:

std::count_if and then compare the result to 1.

To avoid traversing the whole container in case eg the first two elements already match the predicate I would use two calls looking for matching elements. Something along the line of

auto it = std::find_if(begin,end,predicate); if (it == end) return false; ++it; return std::none_of(it,end,predicate); 

Or if you prefer it more compact:

auto it = std::find_if(begin,end,predicate);  return (it != end) && std::none_of(std::next(it),end,predicate); 

Credits goes to Remy Lebeau for compacting, Deduplicator for debracketing and Blastfurnance for realizing that we can also use none_of the std algorithms.

like image 125
463035818_is_not_a_number Avatar answered Sep 25 '22 20:09

463035818_is_not_a_number