温馨提示×

c++ all_of与any_of的区别

c++
小樊
81
2024-09-04 18:52:16
栏目: 编程语言

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

  1. 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;
}
  1. 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 只需要存在至少一个满足条件的元素。根据你的需求选择合适的算法。

0