#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//内置数据类型
void test(){
vector<int>v;
v.push_back(1);
v.push_back(2);
v.push_back(1);
v.push_back(1);
int num=count(v.begin(),v.end(),1);
cout<<"1的个数为:"<<num<<endl;
}
//自定义数据类型
class Person{
public:
string m_Name;
int m_Age;
Person(string name,int age){
m_Name=name;
m_Age=age;
}
bool operator==(const Person & p){
if(this->m_Age=p.m_Age){
return true;
}else{
return false;
}
}
};
void test2(){
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 10);
Person p4("ddd", 10);
Person p5("eee", 10);
vector<Person>v1;
v1.push_back(p1);
v1.push_back(p2);
v1.push_back(p3);
v1.push_back(p4);
v1.push_back(p5);
Person p("eee", 10);
int num=count(v1.begin(),v1.end(),p);
cout<<"与p1年龄相同的个数:"<<num<<endl;
}
int main(){
test();
test2();
return 0;
}
常用查找算法-count
最新推荐文章于 2024-09-12 11:35:40 发布
这篇博客演示了如何在C++中利用STL的`count`函数来统计内置类型(如整数)和自定义类型(如`Person`类)的出现次数。首先,通过`vector<int>`展示了计数内置类型元素的例子,接着定义了一个`Person`类,并重载了`==`运算符,以便在`vector<Person>`中计算相同年龄的`Person`对象数量。
摘要由CSDN通过智能技术生成