重载,排序,集合实例

#include <ios>
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>

//using std::vector;
//using std::cin;
//using std::cout;
//using std::string;
//using std::setprecision;
//using std::endl; 
//using std::domain_error;
//using std::istream;
//using std::max;
//using std::ios;
//using std::setw;
using namespace std;

//查找中值
double median(vector<double> vec)
{
    vector<double>::size_type size=vec.size();
    if(size==0)
    {
        throw domain_error("你没有家庭作业!");
    }
    sort(vec.begin(),vec.end());
    vector<double>::size_type mid=size/2;

    return size%2==0?(vec[mid]+vec[mid-1])/2:vec[mid];
}
//计算成绩
double grade(double mid,double final,double homework)
{
    return 0.2*mid+0.4*final+0.4*homework;
}

double grade(double mid,double final,const vector<double> & vec)
{
    if(vec.size()==0)
    {
        throw domain_error("你没有家庭作业!");
    }
    return     grade(mid,final,median(vec));
}

//读家庭作业
istream& read_hw(istream& in,vector<double>& hw)
{
    if(in)
    {
        hw.clear();
        double x;
        while(in>>x)
        {
            hw.push_back(x);
        }
        in.clear();
    }
    return in;
}

 
struct Student_Info
{ 
    string name;
    double mid;
    double final;
    vector<double> homeworks;
};

//读一个学生的信息
istream& read(istream& is,Student_Info& s)
{
    is>>s.name>>s.mid>>s.final;
    read_hw(is,s.homeworks);
    return is;
}

double grade(const Student_Info& s)
{
    return grade(s.mid,s.final,s.homeworks);
}

bool Compare(const Student_Info& a,const Student_Info& b)
{
    return a.name<b.name;
}

int main()
{
   vector<Student_Info> students;
   Student_Info student;
   string::size_type maxLen=0;

   while(read(cin,student))
   {
       maxLen=max(maxLen,student.name.size()); //max在库<algorithm>中定义的
       students.push_back(student);
   }

   sort(students.begin(),students.end(),Compare); //这样使排序的时候按照名字排列。

   for(vector<Student_Info>::size_type i=0;i!=students.size();++i)
   {
       cout.setf(ios::left); //是数据左对齐
       cout<<setw(maxLen+1)<<students[i].name;
       try{
        double final_grade=grade(students[i]);
        std::streamsize prec=cout.precision(); //类型streamsize在<ios>中,输入/输出库用其来表示长度。
        cout<<setprecision(3)<<final_grade<<setprecision(prec); //控制器setprecision在<iomanip>中,这个控制器可以让我们指明要包含的有效位数。
       }
       catch(domain_error e)
       {
           cout<<e.what();//输出错误!
       }
       cout<<endl;
   } 
   return 0;
}


//上面的程序在一个文件中显的太乱,可以分成多个文档。这个时候需要避免多次包含的情况。
//避免办法
#ifndef xxx
#define xxx
//代码
#endif
原文地址:https://www.cnblogs.com/hometown/p/3363876.html