简单的程序诠释C++ STL算法系列之七:count_if

C++STL的非变易算法(Non-mutating algorithms)是一组不破坏操作数据的模板函数,用来对序列数据进行逐个处理、元素查找、子序列搜索、统计和匹配。

count_if算法是使用谓词判断pred统计迭代器区间[first , last) 上满足条件的元素个数n,按计数n是否引用返回,有如下两种函数原型:

函数原型:

template<class InputIterator, class Predicate> typename iterator_traits<InputIterator>::difference_type count_if( InputIterator _First, InputIterator _Last, Predicate _Pred );
template<class InputIterator, class T> inline size_t count( InputIterator First, InputIterator Last, const T& Value )


示例代码:

/******************************************************************* * Copyright (C) Jerry Jiang * File Name : count_if.cpp * Author : Jerry Jiang * Create Time : 2011-10-9 19:46:25 * Mail : jbiaojerry@gmail.com * Blog : http://blog.csdn.net/jerryjbiao * Description : 简单的程序诠释C++ STL算法系列之七 * 非变易算法 : 条件统计容器元素个数count_if ******************************************************************/ #pragma warning(disable:4786) #include <algorithm> #include <map> #include <iostream> using namespace std; //学生记录结构体 struct stuRecord{ struct stuInfo{ char* name; int year; char* addr; }; int id; //学号 stuInfo m_stuInfo; //学生信息 stuRecord(int m_id, char* m_name, int m_year, char* m_addr) { id = m_id; m_stuInfo.name = m_name; m_stuInfo.year = m_year; m_stuInfo.addr = m_addr; } }; typedef stuRecord::stuInfo stuRI; bool setRange( pair<int, stuRI> s ) { if (s.second.year > 20 && s.second.year < 30) { return true; } return false; } int main() { //学生数据 stuRecord stu1 = stuRecord(1, "张三", 21, "北京"); stuRecord stu2 = stuRecord(2, "李四", 29, "上海"); stuRecord stu3 = stuRecord(3, "王五", 12, "深圳"); stuRecord stu4 = stuRecord(4, "赵六", 25, "长沙"); stuRecord stu5 = stuRecord(5, "孙七", 30, "广东"); //插入学生记录 map<int, stuRI> m; m.insert(make_pair(stu1.id, stu1.m_stuInfo)); m.insert(make_pair(stu2.id, stu2.m_stuInfo)); m.insert(make_pair(stu3.id, stu3.m_stuInfo)); m.insert(make_pair(stu4.id, stu4.m_stuInfo)); m.insert(make_pair(stu5.id, stu5.m_stuInfo)); //条件统计 int num = count_if(m.begin(), m.end(), setRange); cout << "学生中年龄介于20至30之间的学生人数为:" << num << endl; return 0; }

*******************************************************************************************************************************

C++经典书目索引及资源下载:http://blog.csdn.net/jerryjbiao/article/details/7358796

********************************************************************************************************************************


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值