泛型算法名称 |
count() 计数 |
作用 |
在容器中搜索需要计数的值,计算有多少个该值,返回整形 |
参数 |
容器开头, 容器结尾,需要计数的值 |
泛型算法名称 |
count_if() 有条件计数 |
作用 |
在容器中搜索满足条件的值,计算有多少个该值,返回整形 |
参数 |
容器开头, 容器结尾,仿函数(条件) |
//创建容器
vector<int> CreateVector()
{
vector<int> VeInt;
VeInt.push_back(1);
VeInt.push_back(2);
VeInt.push_back(2);
VeInt.push_back(3);
VeInt.push_back(2);
VeInt.push_back(4);
VeInt.push_back(5);
VeInt.push_back(5);
VeInt.push_back(6);
VeInt.push_back(1);
return VeInt;
}
//输出容器
void ShowVector(vector<int> VeInt)
{
vector<int>::iterator showVeInt;
for (showVeInt = VeInt.begin(); showVeInt != VeInt.end(); showVeInt++)
{
cout << *showVeInt << " ";
}
cout << endl;
}
//计数
int my_count(vector<int> intvector, int value)
{
return count(intvector.begin(), intvector.end(), value);
}
//有条件计数(仿函数)
int my_count_if_if(int intvecto)
{
return intvecto > 2;
}
//有条件计数
int my_count_if(vector<int> intvector, int value)
{
return count_if(intvector.begin(), intvector.end(), my_count_if_if);
}
//主方法
void main()
{
vector<int> VeInt = CreateVector();
cout << "VeInt" << "\t";
ShowVector(VeInt);
int sum = my_count(VeInt,2);
cout << "\n" << "该容器中存在“2”有:" << sum << "个。" << endl;
int sum1 = my_count_if(VeInt, 2);
cout << "\n" << "该容器中存在大于“2”的有:" << sum1 << "个。" << endl;
}