如何在c++中使用自定义predicate

   2024-09-30 7010
核心提示:在C++中,谓词(Predicate)是一个返回布尔值的函数或函数对象使用函数作为谓词:#include iostream#include vector#include alg

在C++中,谓词(Predicate)是一个返回布尔值的函数或函数对象

使用函数作为谓词:
#include <iostream>#include <vector>#include <algorithm>bool is_even(int n) {    return n % 2 == 0;}int main() {    std::vector<int> numbers = {1, 2, 3, 4, 5, 6};        // 使用 count_if 算法和自定义谓词 is_even    int even_count = std::count_if(numbers.begin(), numbers.end(), is_even);        std::cout << "偶数的数量: " << even_count << std::endl;    return 0;}
使用函数对象(仿函数)作为谓词:
#include <iostream>#include <vector>#include <algorithm>struct IsEven {    bool operator()(int n) const {        return n % 2 == 0;    }};int main() {    std::vector<int> numbers = {1, 2, 3, 4, 5, 6};        // 使用 count_if 算法和自定义谓词 IsEven    int even_count = std::count_if(numbers.begin(), numbers.end(), IsEven());        std::cout << "偶数的数量: " << even_count << std::endl;    return 0;}
使用Lambda表达式作为谓词:
#include <iostream>#include <vector>#include <algorithm>int main() {    std::vector<int> numbers = {1, 2, 3, 4, 5, 6};        // 使用 count_if 算法和Lambda表达式作为谓词    int even_count = std::count_if(numbers.begin(), numbers.end(), [](int n) {        return n % 2 == 0;    });        std::cout << "偶数的数量: " << even_count << std::endl;    return 0;}

这些示例展示了如何在C++中使用自定义谓词。你可以根据需要选择使用函数、函数对象或Lambda表达式作为谓词。

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

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