Is it possible to use a single call of std::all_of()
and use multiple elements/conditions or'd together? Or does this violate the function?
Example:
if(std::all_of(vector.begin(), vector.end(), 0||1||2||3) == true)
{
//do something
}
Thanks,
The third argument is a single predicate, but you can compose multiple predicates together. With a lambda this looks like:
std::all_of(vector.begin(), vector.end(), [](auto &&v) {
return v == 1 || v == 2 || v == 3 || v == 4;
})
The composition takes place such that the result of the composition itself is a predicate, ie a single function object.
Note that in your example std::all_of(vector.begin(), vector.end(), 0||1||2||3)
you are not passing a predicate. A predicate is a function or function object . 0 || 1 || 2 || 3
0 || 1 || 2 || 3
is not a predicate and so this is not an example of a correct usage of all_of
. This is not dependent on the use of ||
. Just passing a value such as 1
is also incorrect.
You would have to use a predicate such as
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
}
to get the behavior you want.
From cppreference.com you get that
template< class InputIt, class UnaryPredicate >
bool all_of( InputIt first, InputIt last, UnaryPredicate p );
where
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
.
where the most important part for you is the signature of pred
bool pred(const Type &a);
which means that the functor/lambda/method that you use as pred
should take a parameter of type Type
and return a bool
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.