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)参数内的元素数。

无涯教程网

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

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

技术教程推荐

代码精进之路 -〔范学雷〕

重学前端 -〔程劭非(winter)〕

许式伟的架构课 -〔许式伟〕

深入浅出计算机组成原理 -〔徐文浩〕

互联网人的英语私教课 -〔陈亦峰〕

大数据经典论文解读 -〔徐文浩〕

玩转Vue 3全家桶 -〔大圣〕

深入浅出分布式技术原理 -〔陈现麟〕

计算机基础实战课 -〔彭东〕

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