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

2014-11-24 12:43:49 · 作者: · 浏览: 1

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

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

函数原型:

template

typename iterator_traits::difference_type count_if(

InputIterator _First,

InputIterator _Last,

Predicate _Pred

);

template 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

#include

#include

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 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 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;

} 摘自:Jerry.Jiang的程序人生