一个常见的编程题(C++版)

来源:互联网 发布:淘宝买的入职体检报告 编辑:程序博客网 时间:2024/06/17 22:14
  • 题目描述1

这里写图片描述
牛客网上发现的题目,有多种解法,不得不说下面这个解法(参考他人实现)是简洁明了的好实现。从这个代码中看到了平时笔试不常用的库函数,学到了很多。

#include<iostream>#include<vector>#include<algorithm>bool compare(std::pair<std::string,int> const&a,std::pair<std::string,int> const& b){    return a.second>b.second;}int main(){    std::string str,file;    std::vector<std::pair<std::string,int>> errors;    while(getline(std::cin,str)){  //使用getline按行读取,避免了遇到空格被截断的错误        int index=str.rfind('\\');  //rfind反向查找响应的字符所在的位置,'\\'防止转义字符'\'被转义        file=str.substr(index+1);//截取符合条件的子串        errors.push_back(std::make_pair(file,1));//将符合条件的输入做一个pair并记录        for(int i=0;i<errors.size()-1;++i){            if(errors[i].first==file){  //遇到相同文件的计数+1,文件不记录                errors[i].second++;                errors.pop_back();                break;            }        }    }    stable_sort(errors.begin(),errors.end(),compare);//稳定排序,方式乱序,同时自定义比较函数    int count=0;    while(count<8&&count<errors.size()){  //输出结果        int index=errors[count].first.find(' ');        if(index>16){ //如果文件名长于16,进行截取            errors[count].first.erase(0,index-16);        }        std::cout<<errors[count].first<<" "<<errors[count].second<<std::endl;        count++;    }    return 0;}

持续更新……

原创粉丝点击