1004. 成绩排名 (20)

首先我把问题想复杂了,但是学到很多东西,先看看别人的代码(转载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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值