std::all_of() 的多个 UnaryPredicates
Multiple UnaryPredicates for std::all_of()
是否可以使用单个调用 std::all_of()
并同时使用多个 elements/conditions or'd?或者这是否违反了功能?
示例:
if(std::all_of(vector.begin(), vector.end(), 0||1||2||3) == true)
{
//do something
}
谢谢,
第三个参数是单个谓词,但您可以将多个谓词组合在一起。对于 lambda,这看起来像:
std::all_of(vector.begin(), vector.end(), [](auto &&v) {
return v == 1 || v == 2 || v == 3 || v == 4;
})
组合的发生使得组合本身的结果是一个谓词,即单个函数对象。
请注意,在您的示例中 std::all_of(vector.begin(), vector.end(), 0||1||2||3)
您没有传递谓词。谓词是 函数 或 函数对象 。 0 || 1 || 2 || 3
不是谓词,因此这不是 all_of
正确用法的示例。这与 ||
的使用无关。仅传递 1
之类的值也是不正确的。
您将不得不使用诸如
的谓词
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
的 functor/lambda/method 应该采用 Type
和 return 类型的参数 bool
.
是否可以使用单个调用 std::all_of()
并同时使用多个 elements/conditions or'd?或者这是否违反了功能?
示例:
if(std::all_of(vector.begin(), vector.end(), 0||1||2||3) == true)
{
//do something
}
谢谢,
第三个参数是单个谓词,但您可以将多个谓词组合在一起。对于 lambda,这看起来像:
std::all_of(vector.begin(), vector.end(), [](auto &&v) {
return v == 1 || v == 2 || v == 3 || v == 4;
})
组合的发生使得组合本身的结果是一个谓词,即单个函数对象。
请注意,在您的示例中 std::all_of(vector.begin(), vector.end(), 0||1||2||3)
您没有传递谓词。谓词是 函数 或 函数对象 。 0 || 1 || 2 || 3
不是谓词,因此这不是 all_of
正确用法的示例。这与 ||
的使用无关。仅传递 1
之类的值也是不正确的。
您将不得不使用诸如
的谓词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 typeType
must be such that an object of typeInputIt
can be dereferenced and then implicitly converted toType
.
其中对您来说最重要的部分是 pred
bool pred(const Type &a);
这意味着您用作 pred
的 functor/lambda/method 应该采用 Type
和 return 类型的参数 bool
.