本文共 2258 字,大约阅读时间需要 7 分钟。
我们需要开发一个简单的错误记录功能模块,能够记录出错的代码所在的文件名称和行号。具体要求如下:
输入是一行或多行字符串,每行包括带路径文件名称、行号,两者用空格隔开。文件路径为Windows格式,例如:E:\V1R2\product\fpgadrive.c 1325。
将所有记录统计并输出,格式为:文件名代码行数数目,一个空格隔开。结果按数目从多到少排序,数目相同则按输入顺序排序。若超过8条记录,只输出前8条。文件名若超过16字符,输出最后16字符。
使用哈希表(字典)存储错误记录,键为文件名,值为记录的行号和计数。每次遇到相同文件名和行号的记录,计数增加,若超过8条则处理。
提取文件名,去除路径信息。
使用自定义比较器,按错误计数排序,计数相同按出现顺序排序。
通过哈希表和自定义排序结构实现,时间复杂度为O(n)存储,O(n log n)排序。
#include#include #include #include #include #include #include using namespace std; class Info { public: int rank; // 排序权重 int count; // 错误记录数 string file; // 文件名 Info(int _r, int _c, const string &_s) : rank(_r), count(_c), file(_s) {} bool operator<(const Info &other) const { if (count == other.count) { return rank < other.rank; } return count > other.count; } }; int fun(const char *x) { int len = 0; while (*x++) len++; return len - 1; } int main() { char x[] = {'1','2','3','4'}; int m = fun(x); set errors; ifstream geoFile; geoFile.open("text.txt", ios::in); if (geoFile.is_open()) { string instr; while (getline(geoFile, instr)) { if (instr.empty()) break; size_t lastSlash = instr.rfind('\\'); string file = instr.substr(lastSlash + 1); int count = 1; auto it = errors.begin(); while (it != errors.end() && it->file == file) { count++; it++; } if (it == errors.end()) { errors.insert(Info(1, count, file)); } else { Info &existing = *it; existing.count += count; } } } geoFile.close(); vector result; for (const auto &info : errors) { string trimmed = info.file; size_t pos = trimmed.find(' '); if (pos > 16) { trimmed = trimmed.substr(pos - 16); } result.push_back({info.rank, info.count, trimmed}); } sort(result.begin(), result.end()); int outputCount = min(8, (int)result.size()); for (int i = 0; i < outputCount; ++i) { const Info &info = result[i]; cout << info.file << ' ' << info.count << ' '; } }
通过这种方法,能够高效地处理错误记录,满足要求的存储和排序功能。
转载地址:http://tcok.baihongyu.com/