c++ - std::all_of() 的多个 UnaryPredicates

标签 c++ algorithm vector std

是否可以使用单个 std::all_of() 调用并同时使用多个元素/条件 or'd?或者这是否违反了功能?

例子:

if(std::all_of(vector.begin(), vector.end(), 0||1||2||3) == true)
{
   //do something
}

谢谢,

最佳答案

你必须使用一个谓词,例如

vector<t> v;
if(std::all_of(v.begin(), v.end(), [](const t& el){
    return el == 0 || el == 1 || el == 2 || el == 3;                         
};)
{
   //do something
}

获得你想要的行为。


来自 cppreference.com你明白了

template< class InputIt, class UnaryPredicate >
bool all_of( InputIt first, InputIt last, UnaryPredicate p );

在哪里

p - unary predicate . The signature of the predicate function should be equivalent to the following:

bool pred(const Type &a);

The signature does not need to have const &, but the function must not modify the objects passed to it. The type Type must be such that an object of type InputIt can be dereferenced and then implicitly converted to Type. ​

对您来说最重要的部分是 pred 的签名

bool pred(const Type &a);

这意味着您用作 pred 的仿函数/lambda/方法应该采用 Type 类型的参数并返回 bool

关于c++ - std::all_of() 的多个 UnaryPredicates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35399001/

相关文章:

c++ - 什么时候应该在 C++ 中使用 new 关键字?

c++ - 使用一个函数对两个不同的 vector (每个 vector 都有 "active"bool)进行排序

c++ - 如何加速包含图形数据的文本文件的 io/解析

c++ - 在 C++ 中初始化引用类型

algorithm - 根据距离和方向创建坐标

arrays - 当应用相邻转置时,在亚线性时间内更新数组中的最大子区间和

matlab - 从对角元素以外的元素创建向量

c++ - 带有反向迭代器的 std::vector 上的 std::lower_bound 产生错误的结果

c++ - Hook ExtTextOut 返回意外结果

algorithm - 如何从起点找到二维数组中相邻元素的最大和