在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
來計算數組中偶數元素的個數。