功能描述:
- 统计元素个数
函数原型:
- ount(iterator beg, iterator end, value);
//统计元素出现次数
//beg开始迭代器
//end结束迭代器
//value统计元素
代码演示:
#include<iostream>using namespace std;#include<algorithm>#include<vector>#include<string>//常用查找算法 count//1、统计内置数据类型void test01() {vector<int>a;a.push_back(10);a.push_back(20);a.push_back(40);a.push_back(20);a.push_back(30);a.push_back(40);//统计40出现的次数int num = count(a.begin(), a.end(), 40);cout << "40的元素个数为:" << num << endl;}//2、统计自定义数据类型class Person {public:Person(string name, int age) {this->m_Name = name;this->m_Age = age;}bool operator == (const Person& p) {if (this->m_Age == p.m_Age) {return true;}else {return false;}}string m_Name;int m_Age;};void test02() {vector<Person>v;Person p1("WTY1", 18);Person p2("WTY2", 19);Person p3("WTY3", 20);Person p4("WTY4", 19);Person p5("WWW", 19);v.push_back(p1);v.push_back(p2);v.push_back(p3);v.push_back(p4);int num = count(v.begin(), v.end(), p5);cout << "和WWW同岁数人员个数为:" << num << endl;}int main() {test01();test02();return 0;}
运行结果:
总结:统计自定义数据类型时候,需要配合重载operator==才能进行统计。
