功能描述:

    • 统计元素个数

    函数原型:

    • ount(iterator beg, iterator end, value);

    //统计元素出现次数
    //beg开始迭代器
    //end结束迭代器
    //value统计元素

    代码演示:

    1. #include<iostream>
    2. using namespace std;
    3. #include<algorithm>
    4. #include<vector>
    5. #include<string>
    6. //常用查找算法 count
    7. //1、统计内置数据类型
    8. void test01() {
    9. vector<int>a;
    10. a.push_back(10);
    11. a.push_back(20);
    12. a.push_back(40);
    13. a.push_back(20);
    14. a.push_back(30);
    15. a.push_back(40);
    16. //统计40出现的次数
    17. int num = count(a.begin(), a.end(), 40);
    18. cout << "40的元素个数为:" << num << endl;
    19. }
    20. //2、统计自定义数据类型
    21. class Person {
    22. public:
    23. Person(string name, int age) {
    24. this->m_Name = name;
    25. this->m_Age = age;
    26. }
    27. bool operator == (const Person& p) {
    28. if (this->m_Age == p.m_Age) {
    29. return true;
    30. }
    31. else {
    32. return false;
    33. }
    34. }
    35. string m_Name;
    36. int m_Age;
    37. };
    38. void test02() {
    39. vector<Person>v;
    40. Person p1("WTY1", 18);
    41. Person p2("WTY2", 19);
    42. Person p3("WTY3", 20);
    43. Person p4("WTY4", 19);
    44. Person p5("WWW", 19);
    45. v.push_back(p1);
    46. v.push_back(p2);
    47. v.push_back(p3);
    48. v.push_back(p4);
    49. int num = count(v.begin(), v.end(), p5);
    50. cout << "和WWW同岁数人员个数为:" << num << endl;
    51. }
    52. int main() {
    53. test01();
    54. test02();
    55. return 0;
    56. }

    运行结果:
    image.png
    总结:统计自定义数据类型时候,需要配合重载operator==才能进行统计。