您的位置:首页 > 其它

简单错误记录

2016-07-19 20:57 330 查看
本代码来自网络,参考资料如右链接:https://yq.aliyun.com/articles/3450

主要练习了容器与算法的使用,原代码无法满足机试题的要求,因为题目表述不清,因此对原代码作了小的改动,作了注释

代码

/*---------------------------------------
*   日期:2015-07-02
*   原作者:SJF0115
*   题目:简单错误记录
*   来源:华为机试练习题
*   修改作者:Kaysono012345
*   修改日期:2016-07-19
-----------------------------------------*/
#include<string>
#include<iostream>
#include<vector>
#include<algorithm>
#include<list>
using namespace std;
struct ErrorLog //创建一个数据结构,包含要输出的文件名称、行号与数量
{
string name;
string line;
int count;
};
ErrorLog CreateErrorLog(string name, string line)//根据输入的包括路径的文件名称与行号,创建新的错误记录结构体变量,创建过程中求取目标文件名称
{
ErrorLog log;
int namesize = name.size();
for (int i = name.size(); i >= 0; i--)
{
if (name[i] == '\\')
{
name = name.substr(i + 1);//string.substr的运用,取子字符串
break;
}
}
if (name.size() > 16)//仅取最多16个字符的文件名
name = name.substr(name.size() - 16);
log.name = name;
log.line = line;
log.count = 1;//创建新的记录,表示没有旧的记录存在,因此数量目前为1
return log;//返回结构体变量
}
void RecordErrorLog(int &number, ErrorLog log, vector<ErrorLog> &result)//记录错误,输入量包括一条错误记录,输入输出量包括记录总数量,记录结果(用容器表示,可用数组表示多条记录),两者采用引用
{
bool isRepeat = false;
for (string::size_type i = 0; i < result.size(); ++i)//注意采用 string::size_type i,这样i才能与result.size()比较
{
if (log.name == result[i].name &&log.line == result[i].line)
{
isRepeat = true;
++result[i].count;//如果已存在记录,则对已存在记录的数量变量加1
break;
}
}
if (!isRepeat)//如果为新记录,则根据已存在记录数量,分别加入result中,以下注释的三行是为了配合华为机试题的要求,它的要求是输出最新的8条记录,而非原代码所认为的不重复的从头覆盖原记录的总8条记录
{
//if (result.size() < 8)
result.push_back(log);
/*else*/
//result[number % 8] = log;//注意采用result[number % 8]
number++;
}
}
int main()
{
ErrorLog log;
vector<ErrorLog> result;
string name, line;
int number = 0;
while (cin >> name >> line&& name != "quit")//不知道在VS2013调试命令窗口中应该如何退出循环
{
log = CreateErrorLog(name, line);
RecordErrorLog(number, log, result);
}
if (result.size() <= 8){//该段if代码是配合华为机试题的要求,它的要求是输出最新的8条记录
for (string::size_type i = 0; i < result.size(); ++i)
cout << result[i].name << ' ' << result[i].line << ' ' << result[i].count << endl;
}
else{
for (string::size_type i = result.size() - 8; i < result.size(); ++i)
cout << result[i].name << ' ' << result[i].line << ' ' << result[i].count << endl;
}
/*for (string::size_type i = 0; i < result.size(); ++i)
cout << result[i].name << ' ' << result[i].line << ' ' << result[i].count << endl;*/
//该段注释代码为原代码,输出不重复的从头覆盖原记录的总8条记录
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息