溫馨提示×

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

c++
小樊
98
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女