for_each算法的使用 掌握查询算法find
- 求所有学生某门课程成绩的和和平均值,以vector为容器,利用函数对象和for_each算法实现。
- 查找学生成绩为80的学生信息,以vector为容器要求显示格式为“姓名:张三; 学号:001;成绩:80;”。 ,
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
class Student
{
private:
string m_strNO;
string m_strName;
int m_chinesegrade;
int m_mathgrade;
public:
Student(string strNO,string strName,int ChineseGrade,int MathGrade):
m_strNO(strNO),m_strName(strName),
m_chinesegrade(ChineseGrade),m_mathgrade(MathGrade)
{
}
string GetNO() {return m_strNO;}
string GetName() {return m_strName;}
int GetChineseGrade() {return m_chinesegrade;}
int GetMathGrade(){return m_mathgrade;}
bool operator == (int grade)
{
if((this->GetChineseGrade() == grade) || (this->GetMathGrade() == grade))
{
return true;
}
}
};
ostream& operator << (ostream& os, Student& s)
{
os << s.GetNO() << "\t" << s.GetName() << "\t" << s.GetChineseGrade() << "\t" <<s.GetMathGrade();
return os;
}
class PrintIofo
{
private:
int m_Chinesenum = 0;
int m_Mathnum = 0;
int count = 1;
int avgChinese;
int avgMath;
public:
PrintIofo():count(1){}
int GetChinesnum(){return m_Chinesenum;}
int GetManthnum(){return m_Mathnum;}
int Getcount(){return count;}
int GetavgChines(){return avgChinese;}
int GetavgMath(){return avgMath;}
void operator()(Student& s)
{
m_Chinesenum += s.GetChineseGrade();
m_Mathnum += s.GetMathGrade();
avgChinese = m_Chinesenum/count;
avgMath = m_Mathnum/count;
count++;
}
};
typedef vector<Student> LISTSTUD;
int main()
{
LISTSTUD sm1;
Student s1("001", "张三",80,90);
Student s2("002", "李四",70,80);
Student s3("003", "王五",60,90);
sm1.push_back(s1);
sm1.push_back(s2);
sm1.push_back(s3);
PrintIofo p = for_each(sm1.begin(), sm1.end(),PrintIofo());
cout << "语文总成绩 "<<p.GetChinesnum() << "\t"
<< "语文平均成绩"<< p.GetavgChines() << endl
<< "数学总成绩 " << p.GetManthnum() << "\t"
<< "数学平均成绩" << p.GetavgMath()<< endl<<endl;
LISTSTUD::iterator it_find;
it_find = find(sm1.begin(),sm1.end(),80);
if((*it_find).GetChineseGrade() == 80)
{
cout << "姓名:" << (*it_find).GetName() << "\t学号:" << (*it_find).GetNO()
<< "\t语文成绩为:" << (*it_find).GetChineseGrade()<<endl;
}else if((*it_find).GetMathGrade() == 80)
{
cout << "姓名:" << (*it_find).GetName() << "\t学号:" << (*it_find).GetNO()
<< "\t语文成绩为:" << (*it_find).GetMathGrade()<<endl;
}
}