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

avatar
作者
猴君
阅读量:0

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!