一个题搞定freopen/结构体/sort( )排序

第五版  结构体章节 例题

 

(1)首先  因输入数据多行表示,我们改造成  freopen() 结构,下图

 

(2)课本上给出的排序是冒泡排序处理:

   a,基于稳定因素:题面说 输入在前面的排序后也在前面,所以此处用稳定的排序。

  b,在当前学习中因为没接触到排序,我们用 sort( )排序,#include<algorithm> 。

       sort( )排序中 本题结构体作为一个整体,必须让sort( )指定关键字排序  本题是 total.,在cmd中 明确total作为比较关键字(这里一定不能少)。

贴入代码:

#include<algorithm> //algorithm 
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
  struct student
    {
        string name;
        int chinese,math;
        int total;
    }; 
student a[110];
int n;
bool cmp(student a,student b)
{  
   return a.total>b.total;
}
int main()
{
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout); 
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>a[i].name;
        cin>>a[i].chinese>>a[i].math;
        a[i].total=a[i].chinese+a[i].math;
    }
    sort(a,a+n,cmp);
    
    for(int i=0;i<n;i++)
    cout<<a[i].name<<" "<<a[i].chinese<<"  "<<a[i].math<<" "<<a[i].total<<endl;
    return 0;
}

 

贴入_输入数据:

4
gaoxiang  10  10
wangxi 70 99
liujia 90 87
zhangjin 78 91

 

posted on 2019-11-11 19:29  lcdxjsj  阅读(111)  评论(0)    收藏  举报

导航