您的位置:首页 > 其它

非变异算法之计数(count, count_if)

2011-04-26 11:36 357 查看
主要函数

count, count_if.

template<class InIt, class T>
size_t count(InIt first, InIt last, const T& val);

template<class InIt, class Pred>
size_t count_if(InIt first, InIt last, Pred pr);


统计数组中某个元素出现的次数及大于4的元素个数

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;
bool matchExpress(int src)
{
return src > 4;
}
int main(int argc, char *argv[])
{
vector<int>v;

for (int i = 1; i <= 10; i++)
{
int temp;
cin >> temp;
v.push_back(temp);
}

cout << "/n输入要统计的数字: ";
int theOne;
cin >> theOne;

int nCount = count(v.begin(), v.end(), theOne );
cout << theOne << " in total is " << nCount << endl << endl;

int nSize = count_if(v.begin(), v.end(),matchExpress);
cout << "> 4 的数字共有: " << nSize << endl;
system("pause");
return 0;
}


count,count_if 应用于类

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
class Student
{
private:
string stuName;
int stuNumber;
int stuGrade;
public:
Student(const int number = 0, const string name = "none", const int grade = 0);
const int number()const { return stuNumber; }
const string name() const  { return stuName; }
const int grade() const { return stuGrade; }
bool operator ==( const int grade) const { return stuGrade == grade; }
};

Student::Student(const int number, const string name, const int grade)
{
stuNumber = number;
stuName = name;
stuGrade = grade;
}

class matchExpress
{
private:
int grade;
public:
matchExpress(const int grade) { this->grade = grade; }
bool operator()(const Student &stu) const { return stu.grade() == grade; }
};
bool match(Student &stu)
{
return stu.grade() == 80;
}
int main(int argc, char *argv[])
{
Student stu1(10001, "张三",70);
Student stu2(10002, "李四",80);
Student stu3(10003, "王码",90);

vector<Student> stuTable;
stuTable.push_back(stu1);
stuTable.push_back(stu2);
stuTable.push_back(stu3);

int nCount1 = count(stuTable.begin(), stuTable.end(), 80);
int nCount2 = count_if(stuTable.begin(), stuTable.end(), matchExpress(80));
int nCount3 = count_if(stuTable.begin(), stuTable.end(), match);

cout << "分数为80的学生个数为: " << nCount1 << endl;
cout << "分数为80的学生个数为: " << nCount2 << endl;
cout << "分数为80的学生个数为: " << nCount3 << endl;

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: