前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >count_if按条件统计元素个数

count_if按条件统计元素个数

作者头像
大忽悠爱学习
发布2021-03-02 14:44:43
9830
发布2021-03-02 14:44:43
举报
文章被收录于专栏:c++与qt学习

函数原型:

在这里插入图片描述
在这里插入图片描述

自定义数据类型:

代码语言:javascript
复制
#include<iostream>
using namespace std;
#include<deque>
#include<algorithm>
#include<string>
bool a(int val)
{
	return val % 2 == 0;
}
void test01()
{
	deque<int> d;
	d.push_front(6);
	d.push_front(5);
	d.push_front(4);
	d.push_front(3);
	d.push_front(2);
	d.push_front(1);
	cout << count_if(d.begin(), d.end(), a) << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}
在这里插入图片描述
在这里插入图片描述

自定义数据类型:

代码语言:javascript
复制
#include<iostream>
using namespace std;
#include<deque>
#include<algorithm>
#include<string>
class person {
public:
	string name;
	int age;
	person(string n, int a) :name(n), age(a) {}
};
//仿函数
class compare {
public:
 //const可写可不写,最好写上
	bool operator()(const person &p)
	{
		return p.age > 40;
	}
};
void test01()
{
	//count_if
	person p1("孙悟空", 180);
	person p2("沙僧", 60);
	person p3("猪八戒", 80);
	person p4("白骨精", 18);
	person p5("牛魔王", 40);
	deque<person> m = { p1,p2,p3,p4,p5 };
	person p6("二郎神", 30);
	cout << count_if(m.begin(), m.end(), compare());
}
int main()
{
	test01();
	system("pause");
	return 0;
}
在这里插入图片描述
在这里插入图片描述

区别:为什么count那里要加const,这边不要 因为count那里是进行元素比较操作,需要重载==运算符,要让底层识别,所以要加const 而这边是作为条件,将元素放入仿函数中看是否符合条件 总结:最好都加上const

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/02/16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档