C++STL 第八次实验

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39776901/article/details/78639595

【实验要求】
  幼儿园中按班组织学生,每个班学生按学号排号,规模为25个孩子,学校每天出勤用一个bitset描述,1代表出勤,0代表缺勤,试着编写接口函数,输出每个孩子序号与出勤数
  (optional)找出出勤率最高的3个孩子给当月的小红花。

【目标】
  熟悉stl库中<bitset>使用,复习vector与文件io
  从duty.txt中构建vector<bitset<N>>容器
  对于序号/出勤数,显示输出
  (optional)按出勤数排序

一行代表一天,一列代表一个小朋友,要求输出类似第几个小朋友来了几天这样的数据

【文件onduty.txt内容】

1111111111111111111111111
1110111011101110111011100
1101101101101101101101101
1111011110111101111011110
0011101110111101111101111
0011101111011111110111111
1111101111110111111100111
1100111110001111111111110
1111111111111101111111111
1111011111011111111110111

【代码演示】

#include <iostream>
#include <string>
#include <bitset>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

class onduty
{
    int no;
    int c_no;
public:
    int getno()
    {
        return no;
    }
    int getc_no()
    {
        return this->c_no;
    }
    void setno(int no)
    {
        this->no = no;
    }
    void setc_no(int c_no)
    {
        this->c_no = c_no;
    }
    friend struct sortno;
    friend struct print;
};

struct sortno
{
    bool operator()(const onduty& o1,const onduty& o2)
    {
        return o1.c_no > o2.c_no;
    }
};

struct print
{
    bool operator()(const onduty& o1)
    {
        cout << "第"<< o1.no << "个小朋友来了" << o1.c_no << "天" << endl;
    }
};

int main()
{
    char buf[26];
    vector<bitset<25>> v;  //用于将文件中的数据放入bitset容器中
    vector<onduty> v1;   //记录每个孩子的序号以及出勤天数
    char c;
    ifstream in;
    in.open("onduty.txt");
    if(!in)
    {
        cout << "文件打开失败...";
        return 0;
    }

    while(in.getline(buf,26))
    {
        v.push_back((bitset<25>)buf);
    }


    int i;
    for(int j=24;j>=0;j--){
        int count = 0;
        for(i=0;i<v.size();i++)
        {
            if(v[i].test(j)==1){
                count++;
            }
        }
        onduty s1;
        s1.setc_no(count);
        s1.setno(25-j);
        v1.push_back(s1);
    }

    sort(v1.begin(),v1.end(),sortno());

    for_each(v1.begin(),v1.end(),print());

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39776901/article/details/78639595