温馨提示×

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

c++
小樊
81
2024-09-15 16:34:09
栏目: 编程语言

在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表达式作为谓词。

0