是否有STL/boost算法来检查容器中的所有元素是否匹配值?

Gra*_*amS 15 c++ algorithm boost stl

是否有STL/boost算法将测试两个迭代器之间的所有元素是否匹配给定值?或者谓词返回true所有这些?

即类似的东西

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;
}
Run Code Online (Sandbox Code Playgroud)

要么

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;
}
Run Code Online (Sandbox Code Playgroud)

Cas*_*Cow 22

如果你可以否定谓词,你可以使用std :: find/std :: find_if并查看它是否返回序列的结束元素.如果没有,则返回匹配的那个.

您可以使用std :: not1或std :: not_equal_to来调整函数,因此通过与std :: find_if结合使用,您可以使用STL完成此操作而无需编写循环.

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) );
Run Code Online (Sandbox Code Playgroud)

  • 实际上我不认为`not_equal_to()`语法是完全正确的.我可能做错了,但我必须像这样使用`bind2nd`:`std :: find_if(seq.begin(),seq.end(),std :: bind2nd(std :: not_equal_to <MyType> (),val))` (4认同)

fre*_*low 19

C++ 0x介绍std::all_of.