c++ all_of与any_of的区别

   2024-09-30 6840
核心提示:all_of 和 any_of 是 C++ 标准库` 中的两种算法,它们都用于检查容器或范围内的元素是否满足特定条件。all_of:此函数检查容器或

all_ofany_of 是 C++ 标准库` 中的两种算法,它们都用于检查容器或范围内的元素是否满足特定条件。

all_of:此函数检查容器或范围内的所有元素是否都满足给定的条件。如果所有元素都满足条件,则返回 true;否则返回 false

示例:

#include<iostream>#include<vector>#include<algorithm>bool is_positive(int n) {    return n > 0;}int main() {    std::vector<int> numbers = {1, 2, 3, 4, 5};    bool result = std::all_of(numbers.begin(), numbers.end(), is_positive);    if (result) {        std::cout << "All numbers are positive."<< std::endl;    } else {        std::cout << "Not all numbers are positive."<< std::endl;    }    return 0;}
any_of:此函数检查容器或范围内是否存在至少一个元素满足给定的条件。如果存在满足条件的元素,则返回 true;否则返回 false

示例:

#include<iostream>#include<vector>#include<algorithm>bool is_negative(int n) {    return n < 0;}int main() {    std::vector<int> numbers = {-1, 2, 3, 4, 5};    bool result = std::any_of(numbers.begin(), numbers.end(), is_negative);    if (result) {        std::cout << "There is at least one negative number."<< std::endl;    } else {        std::cout << "There are no negative numbers."<< std::endl;    }    return 0;}

总结:all_of 要求容器或范围内的所有元素都满足条件,而 any_of 只需要存在至少一个满足条件的元素。根据你的需求选择合适的算法。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号