zl程序教程

您现在的位置是:首页 >  后端

当前栏目

PAT 1083 List Grades[简单]

List 简单 PAT
2023-09-14 09:11:23 时间
1083 List Grades (25 分)

Given a list of N student records with name, ID and grade. You are supposed to sort the records with respect to the grade in non-increasing order, and output those student records of which the grades are in a given interval.

Input Specification:

Each input file contains one test case. Each case is given in the following format:

N
name[1] ID[1] grade[1]
name[2] ID[2] grade[2]
... ...
name[N] ID[N] grade[N]
grade1 grade2

where name[i] and ID[i] are strings of no more than 10 characters with no space, grade[i] is an integer in [0, 100], grade1 and grade2 are the boundaries of the grade's interval. It is guaranteed that all the grades are distinct.

Output Specification:

For each test case you should output the student records of which the grades are in the given interval [grade1grade2] and are in non-increasing order. Each student record occupies a line with the student's name and ID, separated by one space. If there is no student's grade in that interval, output NONE instead.

Sample Input 1:

4
Tom CS000001 59
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
60 100

Sample Output 1:

Mike CS991301
Mary EE990830
Joe Math990112

Sample Input 2:

2
Jean AA980920 60
Ann CS01 80
90 95

Sample Output 2:

NONE

 题目大意:给出n个学生,姓名id分数,并给出分数区间,要求在分数区间内的学生按分数排序输出。

//这个就很简单啦,我的AC:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Stu{
    string name,id;
    int sco;
};
vector<Stu> allstu;
vector<Stu> stu;
bool cmp(Stu&a,Stu&b){
    return a.sco>b.sco;
}
int main() {
    int n;
    cin>>n;
    string name,id;
    int sco,low,high;
    for(int i=0;i<n;i++){
        cin>>name>>id>>sco;
        allstu.push_back(Stu{name,id,sco});
    }
    cin>>low>>high;
    for(auto it=allstu.begin();it!=allstu.end();){
        if(it->sco<low||it->sco>high){
            it=allstu.erase(it);//
        }else it++;
    }
    if(allstu.size()==0){
        cout<<"NONE";
    }else{
        sort(allstu.begin(),allstu.end(),cmp);
        for(int i=0;i<allstu.size();i++){
            cout<<allstu[i].name<<" "<<allstu[i].id<<'\n';
        }
    }
    return 0;
}

 

//以下是遇到的问题:

1,关于使用vector::erase函数。

 参数是iterator迭代器,转自:https://www.cnblogs.com/zsq1993/p/5930229.html

for(vector<int>::iterator iter=veci.begin(); iter!=veci.end(); iter++)
{
      if( *iter == 3)
             veci.erase(iter);
}

 

乍一看这段代码,很正常。其实这里面隐藏着一个很严重的错误:当veci.erase(iter)之后,iter就变成了一个野指针,对一个野指针进行 iter++ 是肯定会出错的。

for(vector<int>::iterator iter=veci.begin(); iter!=veci.end(); iter++)
{
      if( *iter == 3)
             iter = veci.erase(iter);
}

这段代码也是错误的:1)无法删除两个连续的"3"; 2)当3位于vector最后位置的时候,也会出错(在veci.end()上执行 ++ 操作)

for(vector<int>::iterator iter=veci.begin(); iter!=veci.end(); )
{
     if( *iter == 3)
          iter = veci.erase(iter);
      else
            iter ++ ;
}

 

第三种是正确的写法,学习了!!