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

1949idc 2年前 (2024-09-18) 阅读数 469 #编程语言

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

  1. 使用函数作为谓词:
#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;
}
  1. 使用函数对象(仿函数)作为谓词:
#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;
}
  1. 使用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表达式作为谓词。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业