在C++中,可以使用STL中的count_if
函數(shù)來統(tǒng)計滿足特定條件的元素個數(shù)。該函數(shù)位于<algorithm>
頭文件中。
下面是一個簡單的示例,演示如何使用count_if
函數(shù)統(tǒng)計一個整數(shù)數(shù)組中大于10的元素個數(shù):
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> numbers = {5, 10, 15, 20, 25};
int count = std::count_if(numbers.begin(), numbers.end(), [](int num) {
return num > 10;
});
std::cout << "There are " << count << " numbers greater than 10 in the array." << std::endl;
return 0;
}
在上面的示例中,使用count_if
函數(shù)統(tǒng)計numbers
容器中大于10的元素個數(shù)。在lambda表達式中,定義了一個條件函數(shù),用于判斷元素是否大于10。count_if
函數(shù)會遍歷容器中的每個元素,并將滿足條件的元素個數(shù)返回給count
變量,最終輸出結(jié)果。