count_if

 
// count_if.cpp -- 2011-10-02-22.16
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

using std ::vector ;
using std ::equal_to ;

int _tmain(int argc, _TCHAR* argv[])
{
	int arr1[] = {1, 2, 3, 4, 5, 1, 8, 9} ;
	vector<int> vec1(arr1, arr1 + sizeof arr1 / sizeof (int)) ;

	//	count_if (beg, end, unaryPred) ;
	//	操作前:[beg,end)标示输入序列.unaryPred是一元函数对象.
	//	操作后:确定输入序列中使unaryPred返回true的元素的个数.
	//	返回值:使unaryPred返回true的元素的个数
	//	备注:		无.
	size_t iCount = count_if(vec1.begin(), vec1.end(), bind1st(equal_to<int> (), 1)) ;
	std ::cout << iCount << std ::endl ;

	std ::cin.get() ;

	return 0 ;
}
std::count_if 是 STL 中的一个算法,用于对容器中的元素进行条件统计。它的函数原型如下: ```c++ template <class InputIterator, class Predicate> typename iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last, Predicate pred); ``` 其中,first 和 last 分别表示容器中要进行统计的元素范围,pred 是一个谓词函数,用于对容器中的每个元素进行判断。count_if 函数会遍历容器中的每个元素,对每个元素都调用谓词函数 pred 进行判断,如果返回值为 true,则该元素被认为是符合条件的,计入统计结果。 count_if 函数返回符合条件的元素个数,其类型为 iterator_traits<InputIterator>::difference_type,表示两个迭代器之间的距离,通常是一个整型数。 下面是一个简单的例子,用于说明 std::count_if 算法的用法: ```c++ #include <iostream> #include <vector> #include <algorithm> bool isOdd(int num) { return num % 2 == 1; } int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; // 使用 std::count_if 算法和 isOdd 谓词函数,统计 vec 中奇数的个数 int count = std::count_if(vec.begin(), vec.end(), isOdd); std::cout << "Count: " << count << std::endl; return 0; } ``` 在这个例子中,我们定义了一个谓词函数 isOdd,用于判断一个数是否为奇数。然后,我们使用 std::count_if 算法和 isOdd 谓词函数来统计 vec 容器中奇数的个数。在调用 std::count_if 算法时,需要传入谓词函数 isOdd 作为第三个参数,表示对容器中的每个元素都要调用该函数进行判断。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值