实验要求:
-
幼儿园中按班组织学生,每个班学生按学号排号,规模为25个孩子,学校每天出勤用一个bitset描述,1代表出勤,0代表缺勤。
-
试着编写接口函数输出每个孩子序号与出勤数。
-
(optional)找出出勤率最高的3个孩子给当月的小红花。
实验目标:
-
熟悉stl库中<bitset>使用,复习vector与文件io
-
从duty.txt中构建vector<bitset<N>>容器
-
对于序号/出勤数,显示输出
-
(optional)按出勤数排序
实验文件:
将下面数据复制到D盘目录下建立duty.txt文件(学号一行不复制)
学号1-------------->学号25
1111111111111111111111111
1110111011101110111011100
1101101101101101101101101
1111011110111101111011110
0011101110111101111101111
0011101111011111110111111
1111101111110111111100111
1100111110001111111111110
1111111111111101111111111
1111011111011111111110111
实验代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>
#include <iterator>
#include <functional>
#define N 25 //学生总数
using namespace std;
class Student //学生类
{
public:
int ID;
int AttendDay;
public:
Student(int id,int attendday):ID(id),AttendDay(attendday){}
int GetId()
{
return ID;
}
int GetAttendDay()
{
return AttendDay;
}
};
ostream& operator << (ostream& os,const Student& s)
{
os << s.ID << '\t' << s.AttendDay << endl;
return os;
}
class StudIndex:public binary_function<Student,Student,bool> //按出勤次数对学生进行排序
{
private:
vector<Student>&vStud;
public:
StudIndex(vector<Student>&vStud):vStud(vStud){}
bool operator() (Student a, Student b)
{
return a.AttendDay < b.AttendDay;
}
};
void test()
{
vector<Student>vec_s; //学生容器
vector<bitset<N> >vec_b; //bitset容器
string str;
ifstream in("D:\\duty.txt");
if(!in)
{
cout << "读入文件错误!" << endl;
return;
}
for (int i = 0;i < N; i++)
{
Student s(i,0);
vec_s.push_back(s);
}
while (getline(in,str))
{
bitset<25>b(str);
vec_b.push_back(b);
}
for (int i = 0;i < vec_b.size();i++)
{
for (int j = 0;j < vec_s.size();j++)
{
if (vec_b[i].test(j) == 1)
{
vec_s[j].AttendDay++;
}
}
}
cout << "\t学号" << '\t' << "出勤次数" << endl;
sort(vec_s.begin(),vec_s.end(),StudIndex(vec_s));
cout << '\t' ;
copy(vec_s.begin(),vec_s.end(),ostream_iterator<Student>(cout,"\t"));
cout << "选最后三位同学给与小红花!" << endl;
}
int main()
{
test();
return 0;
}