您的位置:首页 > 游戏 > 游戏 > 房地产网络营销论文_中企动力销售待遇_特色产品推广方案_合肥seo排名扣费

房地产网络营销论文_中企动力销售待遇_特色产品推广方案_合肥seo排名扣费

2024/10/5 19:20:27 来源:https://blog.csdn.net/weixin_48668114/article/details/142334721  浏览:    关键词:房地产网络营销论文_中企动力销售待遇_特色产品推广方案_合肥seo排名扣费
房地产网络营销论文_中企动力销售待遇_特色产品推广方案_合肥seo排名扣费

STL容器中统计算法count, count_if

  • 💢功能
  • 💢非自定义类型举例
  • 💢自定义类型举例

💢功能

  • 🥝count用于统计容器中某个特定元素的个数,使用的是==运算符。
  • 🥝count_if根据指定的条件统计满足条件的元素的个数。
  • 🥝如果统计自定义类型,需要重载==运算符或者自定义pred。

💢非自定义类型举例

👉 👉 👉
count(vec1.begin(), vec1.end(), 5),统计vec1中5的数量。
count_if(vec1.begin(), vec1.end(), [](int val) -> bool {return val > 3;}),统计vec1中满足大于3的元素的数量。

code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;template<typename T>
void print_vector(const vector<T>& vec)
{for (auto i_vec : vec){cout << i_vec << " ";}cout << endl;
}void test01()
{vector<int> vec1 {1, 2, 5, 7, 25, 5, 5, 7, 33, 44};print_vector(vec1);int cnt = count(vec1.begin(), vec1.end(), 5);cout << "count(vec1.begin(), vec1.end(), 5): " << cnt << endl;
}void test02()
{vector<int> vec1 {1, 2, 5, 7, 25, 5, 5, 7, 33, 44};print_vector(vec1);// count_if举例,记录vector中大于3的元素个数int cnt = count_if(vec1.begin(), vec1.end(), [](int val) -> bool {return val > 3;});cout << "(vec1.begin(), vec1.end(), [](int val) -> bool {val > 10;}): " << cnt << endl;
}void main()
{test01();test02();system("pause");
}result:
1 2 5 7 25 5 5 7 33 44
count(vec1.begin(), vec1.end(), 5): 3
1 2 5 7 25 5 5 7 33 44
(vec1.begin(), vec1.end(), [](int val) -> bool {val > 10;}): 8

💢自定义类型举例

👉 👉 👉
自定义类型在使用时,要重载==运算符。
另外,pred也需要重新实现。

code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;class Person
{
public:Person(string name, int age) : m_name(name), m_age(age) {}bool operator==(const Person& per){if ((per.m_name == this->m_name) && (per.m_age == this->m_age)){return true;}else{return false;}}
public:string m_name;int m_age;
};class Greater10
{
public:bool operator()(Person & per){return per.m_age > 10;}
};
void print_vector(const vector<Person> &vec)
{for (auto i_vec : vec){cout << "name: " << i_vec.m_name << ", age: " << i_vec.m_age  << endl;}cout << endl;
}void test01()
{Person p1("张三", 10);Person p2("李四", 11);Person p3("王五", 12);Person p4("赵六", 10);Person p5("王五", 12);vector<Person> vec1;vec1.push_back(p1);vec1.push_back(p2);vec1.push_back(p3);vec1.push_back(p4);vec1.push_back(p5);print_vector(vec1);int cnt = count(vec1.begin(), vec1.end(), p5);cout << "王五的个数: " << cnt << endl;cnt = count_if(vec1.begin(), vec1.end(), Greater10());cout << "年龄大于10的个数: " << cnt << endl;
}void main()
{test01();system("pause");
}result:
name: 张三, age: 10
name: 李四, age: 11
name: 王五, age: 12
name: 赵六, age: 10
name: 王五, age: 12王五的个数: 2
年龄大于10的个数: 3

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com