difference_type count (InputIterator beg, InputIterator end, const T& value);
difference_type count_if (InputIterator beg, InputIterator end, UnaryPredicate op);
功能:
第一形式会计算区间[beg, end)中的元素等于value的元素个数
第二形式会计算区间[beg, end)中令以下一元判断式结果为true的元素个数:op(elem)
备注:
a、返回值型别为difference_type,是表现迭代器间距的型别
b、注意op在函数调用过程中不应该改变自身状态
c、op不应该改动传进来的参数
d、关联式容器(set/multiset,map/multimap)提供了一个等效的成员函数count()用来计算等于某个value或key的元素个数
e、时间复杂度:线性
count算法
注意引用algorithm头文件
int main(int argc, char *argv[])
{
int arrAge[] = {1,3,5,8,20,8};
vector<int> vec(arrAge, arrAge + sizeof(arrAge)/sizeof(arrAge[0]));
int nCount = count(vec.begin(),vec.end(), 8);
cout << nCount << endl;
return 0;
}
count_if算法
class CPeople
{
int m_nAge;
string m_strName;
public:
CPeople(int nAge= 0) :m_nAge(nAge){}
CPeople(int nAge, string strName):m_nAge(nAge),m_strName(strName){}
int get_age() { return m_nAge; }
string get_name() { return m_strName; }
};
class CFindName
{
string m_strName;
public:
CFindName(string strName = ""):m_strName(strName)
{
cout << "名字为[" << m_strName << "]的人数为:";
}
bool operator()(CPeople people)
{
if (people.get_name() == m_strName)
return true;
return false;
}
};
int main(int argc, char *argv[])
{
CPeople arrPeople[] = {CPeople(20,"乔峰"),CPeople(15,"段誉"),CPeople(33,"赵敏"),CPeople(80,"虚竹"),CPeople(7,"白眉大侠"),CPeople(18,"周芷若"),CPeople(50,"南慕容")};
vector<CPeople> vec1(arrPeople, arrPeople + sizeof(arrPeople)/sizeof(arrPeople[0]));
int nCount = count_if(vec1.begin(),vec1.end(), CFindName("段誉"));
cout << nCount << endl;
return 0;
}