在C++中,count_if
是STL中的一個(gè)算法,用于計(jì)算滿(mǎn)足指定條件的元素個(gè)數(shù)。其語(yǔ)法如下:
template <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
其中,first
和 last
分別是要搜索的元素范圍的起始和結(jié)束迭代器。pred
是一個(gè)一元謂詞函數(shù)對(duì)象,用于指定滿(mǎn)足條件的判定條件。count_if
返回一個(gè)整數(shù),表示滿(mǎn)足條件的元素個(gè)數(shù)。
下面是一個(gè)簡(jiǎn)單的示例,演示如何使用count_if
來(lái)計(jì)算一個(gè)容器中偶數(shù)的個(gè)數(shù):
#include <iostream>
#include <vector>
#include <algorithm>
bool isEven(int n) {
return n % 2 == 0;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int numEven = std::count_if(numbers.begin(), numbers.end(), isEven);
std::cout << "There are " << numEven << " even numbers in the vector." << std::endl;
return 0;
}
在這個(gè)示例中,isEven
是一個(gè)自定義的判定條件函數(shù),用于判斷一個(gè)整數(shù)是否為偶數(shù)。count_if
函數(shù)將這個(gè)條件函數(shù)應(yīng)用到容器numbers
中的每個(gè)元素,并統(tǒng)計(jì)滿(mǎn)足條件的元素個(gè)數(shù)。
需要注意的是,count_if
函數(shù)接受的參數(shù)是迭代器,并且可以用于任何支持迭代器的容器類(lèi)型,如vector
、list
、set
等。