Is there an STL/boost algorithm that will test if all the elements between two iterators match a given value? Or alternatively that a predicate returns true
for all of them?
i.e. something like
template<class InputIterator, class T>
InputIterator all_match (InputIterator first, InputIterator last, const T& value)
{
bool allMatch = true;
while(allMatch && first!=last)
allMatch = (value == *first++);
return allMatch;
}
Or
template <class InputIterator, class Predicate>
bool all_true (InputIterator first, InputIterator last, Predicate pred)
{
bool allTrue = true;
while (allTrue && first != last)
allTrue = pred(*first++);
return allTrue;
}
If you can negate the predicate you can use std::find / std::find_if and see if it returns the end element of your sequence. If not then it returns the one that does match.
You can adapt an function with std::not1 or std::not_equal_to so by doing combined with std::find_if you can indeed do so using STL without writing a loop.
bool allMatch = seq.end() == std::find_if( seq.begin(), seq.end(),
std::not_equal_to(val) );
bool allPass = seq.end() == std::find_if( seq.begin(), seq.end(),
std::not1(pred) );
C++0x introduces std::all_of
.
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