1004. 成绩排名 (20)

来源:互联网 发布:自动签到脚本 python 编辑:程序博客网 时间:2024/05/18 00:16

首先我把问题想复杂了,但是学到很多东西,先看看别人的代码(转载http://www.cnblogs.com/Zengineer/p/4318857.html)

#include<iostream>#include<string>using namespace std;class Student{public:    string name;    string sid;    int score;};int main(){    int n,first=0,last=0;    cin>>n;    Student *stu=new Student[n];    for(int i=0;i<n;i++){        cin>>stu[i].name>>stu[i].sid>>stu[i].score;        }    if(n==1){        cout<<stu[0].name<<" "<<stu[0].sid<<endl;        cout<<stu[0].name<<" "<<stu[0].sid<<endl;    }else{        for(int i=1;i<n;i++){            if(stu[first].score<stu[i].score){                first=i;            }            if(stu[last].score>stu[i].score){                last=i;            }        }        cout<<stu[first].name<<" "<<stu[first].sid<<endl;        cout<<stu[last].name<<" "<<stu[last].sid<<endl;        }    delete [] stu;    return 0;}

然后我的代码,但是第三个测试点没有通过,暂时想不出是什么原因,

#include<iostream>#include<string>#include <regex>#include <vector>using namespace std; int main() { vector<string> str; string nn; int maxI = 0, minI = 0; int max = 0; int min = 100; string temp; regex r("( \\d+)"); smatch match; getline(cin, nn); int n = stoi(nn); while (n--) { getline(cin,temp); str.push_back(temp); } int ii = 0; for (auto& element : str) { if (regex_search((element), match, r)) { int i = stoi(match[1]); if (i > max) { max = i; maxI = ii; } if (i < min) { minI = ii; min = i; } } ii++; } string a = str[maxI]; string b = str[minI];  int num = 0; for (int i = 0;i < a.length();i++) { if (num == 0&&a[i]==' ') num++; else  if (num == 1 && a[i] == ' ') { for (int j = 0;j < i;j++) cout << a[j]; cout << endl; break; } } num = 0; for (int i = 0;i < b.length();i++) { if (num == 0 && b[i] == ' ') num++; else if (num == 1 && b[i] == ' ') { for (int j = 0;j < i;j++) cout <<b[j]; break; } } int aa; cin >> aa; return 0;  }
1. 读入一行字符串包括空格应使用getline函数,但是先使用cin再使用getline回跳过一次getline(http://blog.csdn.net/cjmcp/article/details/24597365),'\n'被getline获取了,解决办法是在getline(cin,line)之前添加一句:cin.ignore();忽略之前的'\n',这样getline就恢复正常了。

2.使用了vector容器

3.使用了正则表达式以及如何从字符串中提取一个字符串,regex r(" ()"),引号里面是捕捉块,至少有一个括号;

smatch m,m[i]返回第i个捕捉块中的字符串。



1 0
原创粉丝点击