一.std::any_of
any_of与下列函数等效:
template<class InputIterator, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) return true;
++first;
}
return false;
}
检测在范围[first, last)内是有任意元素满足条件,如果有任意元素满足条件,返回true,否则返回false,当范围[first, last)为空时(无元素),返回false
// any_of example
#include <iostream> // std::cout
#include <algorithm> // std::any_of
#include <array> // std::array
int main () {
std::array<int,7> foo = {0,1,-1,3,-3,5,-5};
if ( std::any_of(foo.begin(), foo.end(), [](int i){return i<0;}) )
std::cout << "There are negative elements in the range.\\n";
return 0;
}
二.std::all_of
all_of与下列函数等效:
template<class InputIterator, class UnaryPredicate>
bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last) {
if (!pred(*first)) return false;
++first;
}
return true;
}
检测在范围[first, last)内是否所有元素都满足条件,如果所有元素都满足条件,返回true,否则返回false,当范围[first, last)为空时(无元素),返回true
// all_of example
#include <iostream> // std::cout
#include <algorithm> // std::all_of
#include <vector> // std::vector
int main () {
std::vector<int> foo = {3,5,7,11,13,17,19,23};
if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
std::cout << "All the elements are odd numbers.\\n";
return 0;
}
三.std::none_of
none_of与下列函数等效:
template<class InputIterator, class UnaryPredicate>
bool none_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) return false;
++first;
}
return true;
}
检测在范围[first, last)内是否所有元素都不满足条件,如果所有元素都不满足条件,返回true,否则返回false,当范围[first, last)为空时(无元素),返回true
// none_of example
#include <iostream> // std::cout
#include <algorithm> // std::none_of
#include <vector> // std::vector
int main () {
std::vector<int> foo = {1,2,4,8,16,32,64,128};
if ( std::none_of(foo.begin(), foo.end(), [](int i){return i<0;}) )
std::cout << "There are no negative elements in the range.\\n";
return 0;
}
四.对比
input range contains | ||||
---|---|---|---|---|
all true, none false |
some true, some false |
none true, all false |
none true, none false (empty range) |
|
all_of | true | false | false | true |
any_of | true | true | false | false |
none_of | false | false | true | true |
参考链接: all_any_none_of
原文链接:https://blog.csdn.net/caoshangpa/article/details/78541318
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容