華為機試題2016(一) 簡單錯誤記錄
一:簡單錯誤記錄
開發一個簡單錯誤記錄功能小模組,能夠記錄出錯的程式碼所在的檔名稱和行號。
處理:
1.記錄最多8條錯誤記錄,對相同的錯誤記錄(即檔名稱和行號完全匹配)只記錄一條,錯誤計數增加;(檔案所在的目錄不同,檔名和行號相同也要合併)
2.超過16個字元的檔名稱,只記錄檔案的最後有效16個字元;(如果檔名不同,而只是檔名的後16個字元和行號相同,也不要合併)
3.輸入的檔案可能帶路徑,記錄檔名稱不能帶路徑
輸入描述:
一行或多行字串。每行包括帶路徑檔名稱,行號,以空格隔開。
檔案路徑為windows格式
如:E:\V1R2\product\fpgadrive.c 1325
輸出描述:
將所有的記錄統計並將結果輸出,格式:檔名程式碼行數數目,一個空格隔開,如: fpgadrive.c 1325 1
結果根據數目從多到少排序,數目相同的情況下,按照輸入第一次出現順序排序。
如果超過8條記錄,則只輸出前8條記錄.
如果檔名的長度超過16個字元,則只輸出後16個字元
輸入例子:
E:\V1R2\product\fpgadrive.c 1325
輸出例子:
fpgadrive.c 1325 1
思路:
建一個結構體ErrorLog,包含檔名,行號,錯誤數量
結果資料集vector<ErrorLog> res,
對於輸入的每一個<filePath, line>對,得到<fileName,line> 然後和res裡面的每條記錄比較,看是否存在一條記錄其<檔名,行號>和輸入相等,若是,則記錄count++;否則,將輸入新增到res中;這樣處理完所有輸入之後,
對vector按照ErrorLog的count欄位進行排序,
sort(res.begin(), res.end(),Compare)
其中 Compare函式為:
static bool Compare(const ErrorLog& a, const ErrlrLog& b)
{
return a.count>b.count;
}
#include<iostream> #include<string> #include<vector> #include<map> #include<algorithm> using namespace std; struct ErrorLog { string name; int line; //最好寫成int型 int count; }; ErrorLog CreateErrorLog(string name, int line) { ErrorLog log; int nameSize = name.length(); int index = -1; for (int i = nameSize - 1; i >= 0; --i) { if (name[i] == '\\') //注意! { index = i; break; } } name = name.substr(index + 1); log.name = name; log.line = line; log.count = 1; return log; } void RecordErrorLog(int number, ErrorLog log, vector<ErrorLog>& res) { bool isrepeat = false; for (int i = 0; i < res.size(); ++i) { if (res[i].name == log.name && res[i].line == log.line) { res[i].count++; isrepeat = true; break; } } if (isrepeat == false) { //if (res.size() < 8) //{ res.push_back(log); //} } } static bool Compare(const ErrorLog& a, const ErrorLog& b) { return a.count>b.count; } int main() { string name; int line; vector<ErrorLog> result; int number = 8; while (cin>>name>>line) { ErrorLog log = CreateErrorLog(name, line); RecordErrorLog(number, log, result); } sort(result.begin(), result.end(),Compare);//升序排序 for (int i = 0; i < 8; ++i) { int len = result[i].name.length(); if (len>16) result[i].name = result[i].name.substr(len - 16); cout << result[i].name << " " << result[i].line << " " << result[i].count << endl; } }