18.2.4【STL常用查找算法count】
1 #include<iostream> 2 #include<cstdlib> 3 using namespace std; 4 #include<vector> 5 #include<algorithm> 6 #include<string> 7 8 9 /* 10 5.2.5 count 11 统计元素个数 12 count(iterator beg, iterator end, value); 13 // 统计元素出现次数 14 // beg 开始迭代器 15 // end 结束迭代器 16 // value 统计的元素 17 统计自定义数据类型时候,需要配合重载 operator== 18 */ 19 20 21 void test525() //内置数据类型 22 { 23 vector<int> v; 24 v.push_back(1); 25 v.push_back(2); 26 v.push_back(4); 27 v.push_back(5); 28 v.push_back(2); 29 v.push_back(4); 30 v.push_back(4); 31 v.push_back(3); 32 v.push_back(4); 33 34 int num = count(v.begin(), v.end(), 4); 35 cout << "num of 4 in v:" << num << endl; 36 } 37 38 39 class Person 40 { 41 public: 42 string name; 43 int age; 44 45 public: 46 Person(string _name, int _age) 47 { 48 this->name = _name; 49 this->age = _age; 50 } 51 52 bool operator==(const Person & p) 53 { 54 if(this->age == p.age) 55 { 56 return true; 57 } 58 return false; 59 } 60 }; 61 62 63 void test525_1() //自定义数据类型 64 { 65 vector<Person> vv; 66 Person p1("aaa", 10); 67 Person p2("bbb", 20); 68 Person p3("ccc", 30); 69 Person p4("ddd", 30); 70 Person p5("eee", 40); 71 Person p6("fff", 30); 72 vv.push_back(p1); 73 vv.push_back(p2); 74 vv.push_back(p3); 75 vv.push_back(p4); 76 vv.push_back(p5); 77 vv.push_back(p6); 78 79 Person p("zzz", 30); //统计vv中跟zzz年龄相同的有多少人 80 int num = count(vv.begin(), vv.end(), p); 81 cout << "num:" << num << endl; 82 } 83 84 85 int main() 86 { 87 test525(); 88 test525_1(); 89 90 system("pause"); 91 return 0; 92 }