在C++中,謂詞(Predicate)函數是一個返回布爾值的函數,通常用于檢查某種條件是否滿足
#include<iostream>
#include<vector>
#include<algorithm>
// 定義一個謂詞函數,檢查輸入的整數是否為偶數
bool is_even(int num) {
return num % 2 == 0;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 使用std::count_if算法和謂詞函數is_even計算偶數的數量
int even_count = std::count_if(numbers.begin(), numbers.end(), is_even);
std::cout << "Even numbers count: "<< even_count<< std::endl;
return 0;
}
在這個示例中,我們定義了一個名為is_even的謂詞函數,它接受一個整數參數并檢查它是否為偶數。然后,我們使用std::count_if算法和is_even謂詞函數來計算給定整數向量中偶數的數量。
你可以根據需要定義其他類型的謂詞函數,例如檢查字符串是否為空、檢查對象是否滿足特定條件等。在C++標準庫中,謂詞函數通常與算法一起使用,以便在容器中篩選元素或執行其他操作。