一個常見的程式設計題(C++版)
阿新 • • 發佈:2019-01-30
- 題目描述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;
}
持續更新……