谓词(predicate):是做某些检测的函数,返回用于条件判断的类型,指出条件是否成立。

总结:

count       :  在序列中统计某个值出现的次数

count_if   :    在序列中统计与某谓词匹配的次数

count和count_if函数是计数函数,先来看一下count函数:
count函数的功能是:统计容器中等于value元素的个数。

先看一下函数的参数:
count(first,last,value); first是容器的首迭代器,last是容器的末迭代器,value是询问的元素。

可能我说的不太详细,来看一个例题:
给你n个数字(n<=1000),再给你一个数字m,问你:数字m在n个数字中出现的次数。

看到这道题,我们会想到使用sort+equal_range函数的配合(n的范围大约在1万---10万左右),不过n<=1000 数据量不大,所以我们可以直接使用count函数,这里我们要注意一点:count函数的复杂度是线性的,最坏情况是O(n)。这题很简单,所以我们很快就可以写出代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int n;
vector <int> V;
cin>>n;
for(int i=0;i<n;i++)
{
int temp;
cin>>temp;
V.push_back(temp);
}
int ask;
while(cin>>ask)
{
int num=count(V.begin(),V.end(),ask);
cout<<num<<endl;
}
return 0;
}

  

但是,假如我们要使用STL的函数 统计1-10奇数的个数,怎么办呢?

所以,我们就需要使用count_if函数,这是一个很有用的函数,我们要重点介绍它。

看一下count_if函数的参数:
count_if(first,last,value,cmp); first为首迭代器,last为末迭代器,value为要查询的元素,cmp为比较函数。

其实cmp比较函数才是整个count_if函数的核心,cmp比较函数是编程的人写的,返回值是一个布尔型,我相信看完我的例题后,就可以理解这个函数的应用。例题:统计1-10奇数的个数(我的代码):

  

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(int num)
{
return num%2;
}
int main()
{
vector <int> V;
for(int i=1;i<=10;i++)
V.push_back(i);
cout<<count_if(V.begin(),V.end(),comp)<<endl;
return 0;
}

  

成绩大于90

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
struct student
{
string name;
int score;
};
bool compare(student a)
{
return <a.score;
}
int main()
{
int n;
cin>>n;
vector<student> V;
for(int i=;i<n;i++)
{
student temp;
cin>>temp.name>>temp.score;
V.push_back(temp);
}
cout<<count_if(V.begin(),V.end(),compare)<<endl;
return ;
}

最新文章

  1. 收集的github的东西
  2. [C#搜片神器] 之P2P中DHT网络爬虫原理
  3. iOS 手势大全
  4. spring事务传播机制实例讲解
  5. UESTC 1425 Another LCIS
  6. chrome偶尔弹出新窗口的解决方案
  7. Bootstrap: 样式CSS:carousel轮换 图片的使用
  8. ubuntu Linux离线安装软件包
  9. nginx 1.4.2 安装笔记
  10. 使用TensorFlow中的Batch Normalization
  11. 辨析element.offsetXxxx和element.style.xxxx
  12. postman进行接口测试
  13. springboot org.hibernate.MappingException: No Dialect mapping for JDBC type: -9
  14. WCF 客户端调用服务操作的两种方法
  15. thinkphp 自动跟新时间
  16. go语言数组与切片比较
  17. js实现把textarea通过换行或者回车把多行数字分割成数组,并且去掉数组中空的值。
  18. Elasticsearch.js 发布 —— 在Node.js和浏览器中调用Elasticsearch
  19. 011. 解决VS2015中CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
  20. Tortoise svn 冲突解决主要办法

热门文章

  1. HDU:2222-Keywords Search(AC自动机模板,匹配模拟)
  2. P1101 单词方阵
  3. 异步消息处理机制,UI更新
  4. DiyCode开源项目 TopicActivity 分析
  5. CodeForces 768E Game of Stones 打表找规律
  6. java多线程安全的问题
  7. asp.net中使用ffmpeg
  8. bash shell命令与监测的那点事(三)
  9. Stephen 博客正式开通 【个人公众号:Stephen 】
  10. MOCTF-火眼金睛