温馨提示×

如何自定义c++ all_of的谓词函数

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

std::all_of 是 C++ 标准库中的一个算法,用于检查容器或范围内的所有元素是否都满足特定条件

#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 all_positive = std::all_of(numbers.begin(), numbers.end(), is_positive);

    if (all_positive) {
        std::cout << "All numbers are positive."<< std::endl;
    } else {
        std::cout << "Not all numbers are positive."<< std::endl;
    }

    return 0;
}

在这个示例中,我们定义了一个名为 is_positive 的谓词函数,该函数接受一个整数参数并返回一个布尔值,表示该整数是否为正数。然后,我们使用 std::all_of 算法和自定义谓词函数来检查 numbers 向量中的所有元素是否都是正数。

你可以根据需要修改谓词函数以检查其他条件。只需确保谓词函数接受正确的参数类型并返回一个布尔值。

0