C++ 算法 中的 count_if函数

首页 / C++入门教程 / C++ 算法 中的 count_if函数

C++算法count_if()函数具有'pred'值,并返回pred值为true的[first,last)参数内的元素计数。

count_if - 语法

template <class InputIterator, class UnaryPredicate>

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

count_if - 参数

first:它是参数中第一个元素的输入迭代器。

last:它是参数中最后一个元素的输入迭代器。

val :这是在参数中搜索其出现的元素。

count_if - 返回值

该函数返回pred值为true的[first,last)参数内的元素数。

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-algorithm-count-if-function.html

来源:LearnFk无涯教程网

count_if - 例子1

#include<iostream>
#include<algorithm>
#include<vector>
bool isOdd(int k)
{
	return((k%2)==1);
}
int main()
{
	std::vector<int> newvector;
	for(int k=1; k<10; k++)
	newvector.push_back(k);
	int newcount=count_if(newvector.begin(),newvector.end(),isOdd);
	std::cout<<"newvector contains "<<newcount<<" odd values.\n";
	return 0;
}

输出:

newvector contains 5 odd values.

count_if - 例子2

#include<bits/stdc++.h>
using namespace std;
bool isEven(int k)
{
	if(k%2==0)
	return true;
}
int main()
{
	vector<int> u;
	for(int i=0; i<10; i++)
	{
		u.push_back(i);
	}
	int noEven=count_if(u.begin(),u.end(),isEven);
	cout<<"Count of even number is:"<<noEven;
	return 0;
}

输出:

Count of even number is: 10

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

从0开始学架构 -〔李运华〕

机器学习40讲 -〔王天一〕

从0开始学微服务 -〔胡忠想〕

深入拆解Tomcat & Jetty -〔李号双〕

TypeScript开发实战 -〔梁宵〕

深入浅出云计算 -〔何恺铎〕

编译原理实战课 -〔宫文学〕

林外 · 专利写作第一课 -〔林外〕

给程序员的写作课 -〔高磊〕

好记忆不如烂笔头。留下您的足迹吧 :)