std::all_of
是 C++ 標準庫中的一個算法,用于檢查容器或范圍內的所有元素是否都滿足特定條件
#include<iostream>
#include<vector>
#include<algorithm>
// 自定義謂詞函數
bool is_positive(int n) {
return n > 0;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 使用自定義謂詞函數
bool all_positive = std::all_of(numbers.begin(), numbers.end(), is_positive);
if (all_positive) {
std::cout << "All numbers are positive."<< std::endl;
} else {
std::cout << "Not all numbers are positive."<< std::endl;
}
return 0;
}
在這個示例中,我們定義了一個名為 is_positive
的謂詞函數,該函數接受一個整數參數并返回一個布爾值,表示該整數是否為正數。然后,我們使用 std::all_of
算法和自定義謂詞函數來檢查 numbers
向量中的所有元素是否都是正數。
你可以根據需要修改謂詞函數以檢查其他條件。只需確保謂詞函數接受正確的參數類型并返回一個布爾值。