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 : [email protected]
* 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;
} 摘自:Jerry.Jiang的程序人生