1 //统计元素个数 2 3 #include<iostream> 4 #include<string> 5 #include<vector> 6 #include<algorithm> 7 using namespace std; 8 9 //统计内置数据类型 10 void test01() 11 { 12 vector<int>v; 13 14 v.push_back(10); 15 v.push_back(50); 16 v.push_back(90); 17 v.push_back(30); 18 v.push_back(30); 19 v.push_back(20); 20 v.push_back(30); 21 22 23 int num=count(v.begin(), v.end(), 30); 24 cout << "30的元素个数为: " << num << endl; 25 26 } 27 28 //统计自定义数据类型 29 class Person 30 { 31 public: 32 Person(string name, int age) 33 { 34 this->m_Name = name; 35 this->m_Age = age; 36 } 37 38 bool operator==(const Person &p) 39 { 40 if (this->m_Age == p.m_Age) 41 { 42 return true; 43 } 44 else 45 { 46 return false; 47 } 48 } 49 50 string m_Name; 51 int m_Age; 52 }; 53 void test02() 54 { 55 vector <Person>v; 56 Person p1("张三", 30); 57 Person p2("李四", 40); 58 Person p3("王五", 30); 59 Person p4("赵六", 30); 60 Person p5("孙七", 70); 61 62 v.push_back(p1); 63 v.push_back(p2); 64 v.push_back(p3); 65 v.push_back(p4); 66 v.push_back(p5); 67 68 69 Person p("齐吧", 30); 70 int num = count(v.begin(), v.end(), p); 71 cout << "和诸葛亮岁数一样的人为:" << num << endl; 72 } 73 74 int main() 75 { 76 77 test01(); 78 test02(); 79 80 system("pause"); 81 return 0; 82 }