目录

algorithm::count_if()

描述 (Description)

C ++函数std::algorithm::count_if()返回满足条件的范围内的值出现次数。

声明 (Declaration)

以下是std :: algorithm :: count_if()函数形式std :: algorithm头的声明。

C++98

template <class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);

参数 (Parameters)

  • first - 将迭代器输入到搜索序列的初始位置。

  • last - 将迭代器输入到搜索序列的最终位置。

  • pred - 一元谓词,它接受一个参数并返回bool。

返回值

返回pred返回true的范围内的元素数。

异常 (Exceptions)

如果迭代器上的谓词或操作抛出异常,则抛出异常。

请注意,无效参数会导致未定义的行为。

时间复杂

第一个最后一个之间的距离线性。

例子 (Example)

以下示例显示了std :: algorithm :: count_if()函数的用法。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool predicate(int n) {
   return (n > 3);
}
int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};
   int cnt;
   cnt = count_if(v.begin(), v.end(), predicate);
   cout << "There are " << cnt << " numbers are greater that 3." << endl;
   return 0;
}

让我们编译并运行上面的程序,这将产生以下结果 -

There are 2 numbers are greater that 3.
↑回到顶部↑
WIKI教程 @2018