如果需要判断容器中,全部元素或者任意元素满足或者不满足某个条件,那么你就有必要了解一下 std::all_of、std::any_of、std::none_of。
- std::all_of:容器中是否所有元素都满足某个条件,是,则返回 true,否则返回 false
- std::any_of:容器中是否有一个元素满足某个条件,是,则返回 true,否则返回 false
- std::none_of:容器中是否所有元素都不满足某个条件,是,则返回 true,否则返回 false
#includestd::any_of 应用场景举例:是否字符串中包含大写字母#include #include #include std::function is_even = [](int x) -> bool { return x % 2 ? false : true; }; //使用auto关键字自动推导 auto isEven = [](int x) -> bool { return (std::fmod(x, 2) == 0); }; int main() { //是否容器内所有元素都是偶数 std::vector intArray = { 2, 4, 6, 8, 10 }; bool bIsEven = std::all_of(intArray.begin(), intArray.end(), isEven); if (bIsEven) { std::cout << "yes, all elements is even" << std::endl; } else { std::cout << "no, not all elements is even" << std::endl; } return 0; }
#includestd::none_of 应用场景举例:是否没有低于60分的科目#include #include #include int main() { std::string str = "helloWorld"; bool result = std::any_of(str.begin(), str.end(), ::isupper); if (result) { std::cout << "yes, has upper case letter" << std::endl; } else { std::cout << "no, all element is lower case letter" << std::endl; } return 0; }
#include#include #include int main() { std::vector < int > scores = { 78, 89, 94, 97 }; //是否没有一科分数低于60分 bool result = std::none_of(scores.begin(), scores.end(), [](const int& score) { return score < 60; }); if (result) { std::cout << "yes, all scores are above 60" << std::endl; } else { std::cout << "no, all scores are below 60" << std::endl; } return 0; }



