溫馨提示×

count_if在C++中的遞歸應用

c++
小樊
87
2024-08-23 18:02:32
欄目: 編程語言

在C++中,可以通過遞歸調用count_if函數來實現對數組或容器中元素的遞歸計數操作。下面是一個示例代碼,演示了如何使用遞歸的方式計算數組中滿足某個條件的元素個數:

#include <iostream>
#include <vector>
#include <algorithm>

int count_if_recursive(const std::vector<int>& vec, int index, bool (*predicate)(int)) {
    if (index == vec.size()) {
        return 0;
    } else {
        return (predicate(vec[index]) ? 1 : 0) + count_if_recursive(vec, index + 1, predicate);
    }
}

bool isEven(int num) {
    return num % 2 == 0;
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    int count = count_if_recursive(vec, 0, isEven);

    std::cout << "Number of even elements in the vector: " << count << std::endl;

    return 0;
}

在上面的代碼中,count_if_recursive函數通過遞歸方式遍歷數組vec中的元素,對每個元素調用predicate函數判斷是否滿足條件,如果滿足條件則返回1,否則返回0。最終通過累加返回的結果得到滿足條件的元素個數。在main函數中,通過調用count_if_recursive函數并傳入判斷條件函數isEven來計算數組中偶數元素的個數。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女