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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With