溫馨提示×

c++ all_of與any_of的區別

c++
小樊
107
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女