(C++)STL之面向对象实验:小红花(运用bitset)

(C++)STL之面向对象实验:小红花(运用bitset)_第1张图片

相关知识点运用:

(C++)STL之面向对象实验:小红花(运用bitset)_第2张图片

如下图所示,为学生的出勤情况(从左至右,每一列表示一个学生,1~25号)

(C++)STL之面向对象实验:小红花(运用bitset)_第3张图片

下图是学生出勤情况表数据 (可直接复制到student.txt文件中)

1111111111111111111111111
1110111011101110111011100
1101101101101101101101101
1111011110111101111011110
0011101110111101111101111
0011101111011111110111111
1111101111110111111100111
1100111110001111111111110
1111111111111101111111111
1111011111011111111110111

代码实现

#include 
#include 
#include 
#include 
#include 
#include 
#define N 25 
using namespace std;

class Student
{
public:
	int id;
	int attend;

	Student(int id,int attend) :id(id), attend(attend) {}

	friend ostream& operator << (ostream& os, const Student& s)
	{
		os << s.id << '\t' << s.attend << endl;
		return os;
	}
};

class Sort
{
public :
	vector<Student>& student;
	Sort(vector<Student>& student) :student(student){}
	bool operator() (Student a,Student b){
		return a.attend < b.attend;
	}
};

void count()
{
	vector<Student> stu;      
	
	vector<bitset<N> > bit;      

	string str;

	for (int i = 1; i < N + 1; i++)
	{
		Student s(i, 0);
		stu.push_back(s);
	}

	ifstream in("student.txt");  //读
	if (!in)
	{
		cout << " open failed" << endl;
		return;
	}

	while (getline(in, str))
	{
		bitset<N>b(str);
		bit.push_back(b);
	}
	for (int i = 0; i < bit.size(); i++)
	{
		for (int j = 0; j < stu.size(); j++)
		{
			if (bit[i].test(j) == 1)
			{
				stu[j].attend++;
			}

		}
	}

	cout<< '\t' << "id" << '\t' << "attend" << endl;
	sort(stu.begin(), stu.end(),Sort(stu));
	cout << "\t";
	copy(stu.begin(), stu.end(), ostream_iterator<Student>(cout, "\t"));
	
	for (int i = stu.size()-1; i > stu.size() - 4; i--)
	{
		cout << stu.at(i).id <<" ";
	}
	cout << "三名同学获得小红花" << endl;
}

int main()
{
	count();
	system("pause");
	return 0;
}

运行结果截图

(C++)STL之面向对象实验:小红花(运用bitset)_第4张图片

你可能感兴趣的:(C++之STL的学习)