Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an STL/boost algorithm to check all elements in a container match a value?

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;
}
like image 506
GrahamS Avatar asked Nov 19 '10 12:11

GrahamS


2 Answers

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) );
like image 87
CashCow Avatar answered Sep 20 '22 16:09

CashCow


C++0x introduces std::all_of.

like image 45
fredoverflow Avatar answered Sep 17 '22 16:09

fredoverflow