首页 > 试题广场 >

简单错误记录

[编程题]简单错误记录
  • 热度指数:359144 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}在本题中,我们需要处理文件报错信息,其由出错文件的文件路径和错误行号组成。

\hspace{15pt}文件路径的前三个字母为大写字母 \texttt{A-Z} 、冒号 \texttt{ 和反斜杠 \texttt{ ,代表盘符;随后是若干由小写字母构成的字符串,代表文件夹名,彼此使用单个反斜杠间隔。路径的最后一个反斜杠后是文件名。
\hspace{15pt}我们只在乎文件名(即去掉除了文件名以外的全部信息),且至多保留文件名的最后 16 个字符。

\hspace{15pt}随后,我们需要统计相同的报错信息:
\hspace{23pt}\bullet\,如果两条报错信息保留后 16 个字符后的文件名相同,且行号相同,则视为同一个报错;

\hspace{15pt}相同的报错信息以第一次出现的时间为准,至多输出最后 8 条记录。

输入描述:
\hspace{15pt}本题将会给出 1 \leqq T \leqq 100 条报错信息,确切数字未知,您需要一直读入直到文件结尾;您也可以参考 牛客网在线判题系统使用帮助 获得更多的使用帮助。每条报错信息描述如下:

\hspace{15pt}在一行上先输入一个长度为 1 \leqq {\rm length}(x) \leqq 100 的字符串 x 代表文件路径;随后,在同一行输入一个整数 y \left( 1 \leqq y \leqq 1000 \right) 代表行号。
\hspace{15pt}文件路径的格式如题干所述,保证文件名不为空。


输出描述:
\hspace{15pt}至多八行,每行先输出一个长度为 1 \leqq {\rm length}(s) \leqq 16 的字符串 s ,代表文件名;随后,在同一行输出错误行号、报错次数。
示例1

输入

D:\oblemsinnowcoder 12
D:\nowcoderproblemsinnowcoder 12
D:\nowcoder\problemsinnowcoder 13
D:\oj\problemsinnowcoder 13

输出

oblemsinnowcoder 12 2
oblemsinnowcoder 13 2

说明

\hspace{15pt}在这个样例中,这四条报错信息去除文件路径后,由于文件名长度均超过 16 个字符,故我们只保留最后 16 个字符,得到的文件名均为 \texttt{ 。所以,我们将它们看作同一个文件,按照报错行号划分即可。
示例2

输入

A:\aa 1
B:\b 1
C:\c 1
D:\d 1
E:\e 1
F:\f 1
G:\g 1
H:\h 1
I:\i 1
A:\aa 1

输出

b 1 1
c 1 1
d 1 1
e 1 1
f 1 1
g 1 1
h 1 1
i 1 1

说明

\hspace{15pt}在这个样例中,第一、十条报错信息完全相同,但是我们以其第一次出现的顺序为准,在输出最后 8 条记录时,不包含这一报错。
示例3

输入

D:\zwtymj\xccb\ljj\cqzlyaszjvlsjmkwoqijggmybr 645
E:\je\rzuwnjvnuz 633
C:\km\tgjwpb\gy\atl 637
F:\weioj\hadd\connsh\rwyfvzsopsuiqjnr 647
E:\ns\mfwj\wqkoki\eez 648
D:\cfmwafhhgeyawnool 649
E:\czt\opwip\osnll\c 637
G:\nt\f 633
F:\fop\ywzqaop 631
F:\yay\jc\ywzqaop 631
D:\zwtymj\xccb\ljj\cqzlyaszjvlsjmkwoqijggmybr 645

输出

rzuwnjvnuz 633 1
atl 637 1
rwyfvzsopsuiqjnr 647 1
eez 648 1
fmwafhhgeyawnool 649 1
c 637 1
f 633 1
ywzqaop 631 2
import sys
# 初始化处理错误的函数
def error_format(get_str):
    last_str = get_str.split('\\')
    error_str = last_str[-1].replace('\n', '')
    if len(last_str[-1]) > 20:
        return error_str[-20:]
    return error_str
lines = list(sys.stdin.readlines())
# 存储错误信息的哈希表
lst_error = dict()
for error in lines:
    std_error = error_format(error)
    if std_error in lst_error:
        lst_error[std_error] += 1
    else:
        lst_error[std_error] = 1
# 查找最后八个键
n = len(lst_error.keys())
if n > 8:
    lst_error_end8 = list(lst_error.keys())[-8:]
else:
    lst_error_end8 = list(lst_error.keys())                       
for j in lst_error_end8:
    print(j + ' ' + str(lst_error[j]))

发表于 2022-07-25 18:08:00 回复(0)
题目和以往一样写的一样难懂
发表于 2022-07-02 08:19:11 回复(0)
public class Main {
    public static void main(String[] args) throws IOException {
        HashMap<String, Integer> map = new HashMap<>();
        Deque<Result> deque = new ArrayDeque();
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str=null;
        while ((str = bf.readLine())!=null&&!str.equals("")) {
            String[] split = str.split(" ");
            int hang = Integer.parseInt(split[1]);
            int index = split[0].lastIndexOf("\\");
            String name = split[0].substring(index+1);
            String key = name+hang;
            Result result = new Result();
            result.setName(name);
            result.setHang(hang);
            map.put(key,map.getOrDefault(key,0)+1);
            deque.addLast(result);
        }
        int p = 1;//计数器
        while (!deque.isEmpty()){
            Result result = deque.peekLast();
            Integer num = map.get(result.name + result.hang);
            result.setNum(num);
            System.out.println(result);
            p++;
            if (p>8){
                break;
            }
        }
    }

    static class Result{
        String name;
        int hang;
        int num;

        public void setName(String name) {
            this.name = name;
        }

        public void setHang(int hang) {
            this.hang = hang;
        }

        public void setNum(int num) {
            this.num = num;
        }

        @Override
        public String toString() {
            return name +" "+ hang +" "+ num;
        }
    }
}
为什么无法运行啊!求大佬帮我看看
发表于 2022-06-15 12:03:12 回复(0)
import sys

records = {}
for line in sys.stdin:
    file_path, line_num = line.split(" ")
    file = file_path.split("\\")[-1]
    if len(file) > 16:
        file = file[-16:len(file)]
    rd = file + " " + line_num[:-1] # remove the '\n'
    if rd in records.keys():
        records[rd] += 1
    else:
        records.update({rd:1})
keys = list(records.keys())
last_8_keys = keys[-8:len(keys)]
for key in last_8_keys:
    print(key,records[key], sep=" ")
发表于 2022-06-11 18:41:06 回复(0)
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        HashMap<String, Integer> mapCount = new HashMap<>();
        List<String> list = new ArrayList<>();
        String fileName = "";
        while (in.hasNextLine()) {
            String[] s = in.nextLine().split("\\\\");
            String[] str = s[s.length - 1].split(" ");
            if (str[0].length() > 16) {
                fileName = str[0].substring(str[0].length() - 16,
                                            str[0].length()) + " " + str[1];

            } else {
                fileName = str[0] + " " + str[1];
              
            }
            //------------------------------------------------------------------------------------------------------------
            //上面代码用来获取哈希表需要的key,如D:\zwtymj\xccb\ljj\cqzlyaszjvlsjmkwoqijggmybr 645中的qzlyaszjvlsjmkwoqijggmybr 645
            
            //如果错误记录大于等于8且是之前不重复的记录则将最早查到的错误记录给删除即list中的第一条(list可按存放先后顺序排序)
            if (list.size() >= 8 && !mapCount.containsKey(fileName)) {
                list.remove(0);
                list.add(fileName);

            }
            
            //错误记录小于8且list不存在一样的错误记录(错误文件名+行号)才放入
            if (list.size() < 8 && !list.contains(fileName)) {
                list.add(fileName);
            }
            //将每个错问记录的错问计数放入哈希表对应的values
            int count = mapCount.getOrDefault(fileName, 0) + 1;
            mapCount.put(fileName, count);
        }
        //遍历list可获得要求的错误记录的文件名与行号组成字符串,再由这一字符串找到哈希表对应的错误计数,按要求输出即可
        for (String x : list) {
            System.out.println(x + " " + mapCount.get(x));
        }
    }
}
发表于 2022-04-30 23:49:44 回复(0)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<String> list = new ArrayList();
        while(sc.hasNextLine()){
            String str = sc.nextLine();
            if(str.equals("")){
                break;
            }else{
                list.add(str);
            }
        }
        myfunction(list);
    }

    private static void myfunction(ArrayList<String> list) {
        ArrayList list2 = new ArrayList();
        HashMap<String,Integer> hp = new HashMap();
        for(int i=0;i<list.size();i++){
        int leftindex = list.get(i).lastIndexOf("\\") +1;
        int rightindex = list.get(i).indexOf(" ") - 1;
        String st = rightindex - leftindex + 1 > 16 ?
                list.get(i).substring(rightindex - 15) : list.get(i).substring(leftindex);
            if(hp.containsKey(st)){
                hp.put(st,hp.get(st)+1);
            }else{
                list2.add(st);
                hp.put(st,1);
            }
        }
        int startindex = list2.size() > 8 ? list2.size() - 8 : 0;
        for(int j = startindex ;j<list2.size();j++){
            System.out.println(list2.get(j) + " " + hp.get(list2.get(j)));
        }
    }
}

发表于 2021-10-17 14:16:22 回复(0)
运行时间53ms占用内存12600KB
import java.util.Map;
import java.util.Scanner;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Map<String, Integer> map = new LinkedHashMap<>();
        while (in.hasNextLine()) {
            String input = in.nextLine();
            if (input.length() == 0) {
                break;
            }
            String[] inputArr = input.split("\\s+");
            String[] filePaths = inputArr[0].split("\\\\");
            String fileName = filePaths[filePaths.length - 1];
            String file = fileName.substring(Math.max(fileName.length() - 16, 0));
            String key = file + " " + inputArr[1];
            map.put(key, map.getOrDefault(key, 0) + 1);
        }
        if (map.size() == 0) {
            return;
        }
        int i = 0;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (map.size() - i > 8) {
                i++;
                continue;
            }
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}



发表于 2021-08-22 09:08:58 回复(0)
哈希表+队列,哈希表用于计数,队列用于存储最后8条。
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Map<String,Err> map = new HashMap<>();
        Deque<Err> deque = new LinkedList<>();
        String s = null;
        while(sc.hasNextLine()) {
            // 去掉前面的磁盘名
            s = sc.nextLine().substring(3);
            // 拆分文件与行号
            String[] var1 = s.split(" ");
            // 拆分文件层级
            String[] var2 = var1[0].split("\\\\");
            // 获取错误名
            String errName = var2[var2.length - 1];
            // 获取行号
            String row = var1[1];
            
            Err err = map.get(errName + row);
            if(err == null) {
                // 添加新错误
                err = new Err(errName, row);
                map.put(errName + row, err);
                deque.addLast(err);
                if(deque.size() > 8) {
                    deque.pop();
                }
            } else {
                // 存在错误,累加
                err.count++;
            }
        }
        // 开始输出
        while(!deque.isEmpty()) {
            Err pop = deque.pop();
            String name = pop.name;
            if (name.length() > 16) {
                name = name.substring(name.length() - 16);
            }
            System.out.println(name + " " + pop.row + " " + pop.count);
        }
    }
}

class Err {
    public String name;
    public String row;
    public int count;

    public Err(String name, String row) {
        this.name = name;
        this.row = row;
        this.count = 1;
    }
}


发表于 2021-08-01 17:50:35 回复(0)
#include <iostream>
#include <queue>
#include <string>
#include <map>

using namespace std;

int  main()
{
    string eMessage;
    queue<string> q;
    map<string,int> quants;
    int m=8,n=16;
    while(getline(cin, eMessage))
    {
        size_t pos=eMessage.find_last_of("\\");
        string message=eMessage.substr(pos+1,eMessage.size()-pos-1);
        if(quants.find(message)==quants.end())
        {
            quants.insert(make_pair(message, 1));
            q.push(message);
        }
        else
        {
            quants[message]++;
        }
    }
    while(q.size()>m)
    {
        q.pop();
    }
    for(int i=0;i<q.size();i++)
    {
        int num=quants[q.front()];
        string result=q.front();
        size_t pos=result.find(" ");
        if(pos!=string::npos)
        {
            string temp=result.substr(0,pos);
            if(temp.size()>n)
            {
                result=result.substr(temp.size()-n);
            }
            cout<<result<<" "<<num<<endl;
        }
        q.push(q.front());
        q.pop();
    }
 }

编辑于 2021-06-30 01:03:38 回复(0)
#include<iostream>
#include<string>
#include<deque>
#include<unordered_map>
#include<sstream>
#include<algorithm>

using namespace std;

int main()
{
    string str;
    string item;
    deque<string> str_que;//队列,保持先进先出,保存错误类型
    deque<string> temp_que;//暂时队列,保持先进先出,保存每一条数据中属于错误类型的那一项
    unordered_map<string , int> unique_map;//是否存在相同错误类型

    while(getline(cin, str))
    {
        stringstream ss(str);
        
        while(getline(ss , item , '\\'))//按'\'分割数据,获取错误类型
        {
            //cout<<item<<endl;
            temp_que.push_back(item);//先保存每一段字符
        }

        while(temp_que.size() > 1)
            temp_que.pop_front();//只留下最后一段字符也就是错误类型
        str_que.push_back(temp_que.front());//存入错误类型队列中
        temp_que.clear();//清空暂时队列
        
        if( unique_map.count( str_que.back()) ) //如果出现重复错误类型,计数加一
        {
            auto it = unique_map.find(str_que.back());
            int temp = it->second;
            it->second = temp + 1;
            str_que.pop_back();
        }
        else
            unique_map[str_que.back()] = 1;//如果没有出现重复错误类型,插入错误类型

        if(str_que.size() == 9)//如果队列容量大于八,清除最早的错误类型
            str_que.pop_front();
    }

    while(!str_que.empty())
    {
        if(str_que.front().size() <= 20)
        {
            cout<<str_que.front();
        }
        else
        {
            for(int i = str_que.front().size() - 20 ; i < str_que.front().size() ; i++) //超过16个字符的文件名称,只记录文件的最后有效16个字符;
                cout<<str_que.front()[i];
        }
        cout<<' '<<unique_map[str_que.front()]<<endl;
        str_que.pop_front();
    }
}

发表于 2021-06-09 13:41:58 回复(0)
let data = readline();
let filterArr = [];
let obj = {};
while (data) {
    let arr = data.split(' ')
    let str = arr[0].split('\\').pop()
    if(str.length>16){
        str = str.slice(str.length-16)
    }
    let key = str+' '+arr[1]
    if(filterArr.includes(key)){
        obj[key]++
    }else{
        obj[key] = 1
        filterArr.push(key)
    }
    data = readline();
    if(!data){
        filterArr.slice(filterArr.length-8).map(key=>{
            console.log(`${key} ${obj[key]}`)
        })
    }
}
发表于 2021-04-16 14:21:44 回复(0)

终于解决了,看了评论区的回答才明白,题意的循环记录太坑了。

#-*-coding:utf-8-*-
 import sys
table = {}
name = []
for line in sys.stdin:
    path, num = line.split()
    path = path.split("\\")[-1]
    key = path[-16:] + ' ' + num            # 文件名 + 代码行数相同才算"相同"的错误记录。
    if key not in name:
        if key not in table.keys():            # 题意中未阐述清楚的循环记录。若后面出现的会更新第一次出现的时间,此判断注释即可。
            if len(name) == 8:            # name表中只记录8条错误记录
                name.pop(0)
            name.append(key)
            table[key] = 1
        else:            # 已经出现过的记录的值 +1 。因为不输出,不加也不影响check
            table[key] += 1
    else:            # 正常情况计数
        table[key] += 1
# for i, j in zip(range(len(name)), table.keys()):
for i in range(len(name)):
    print(name[i] + ' ' + str(table[name[i]]))
编辑于 2021-04-13 10:55:03 回复(0)
//常规思路,善用数据结构,主要是队列和哈希

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <queue>

using namespace std;

/*
运行时间:6ms
超过5.33%用C++提交的代码
占用内存:492KB
超过47.31%用C++提交的代码
*/

int main(){
    
    string filepath;
    int line;
    queue<string> errlog;
    unordered_map<string, int> hash;
    
    while(cin >> filepath >> line) {
        int pos = filepath.find_last_of('\\');
        string filename = filepath.substr(pos+1);
        if(filename.length() > 16) {
            string tmp = filename.substr(filename.length()-16);
            filename = tmp;
        }
        string logstr = filename + " " + to_string(line);
        
        if(hash.count(logstr)) {
            hash[logstr] ++;
        } else {
            //一开始理解错了,以为是动态维护8个错误记录
            //实际按题意,先统计错误记录,最后输出最新的8个即可
//             if(errlog.size() >= 8) {
//                 string log = errlog.front();
//                 hash.erase(log);
//                 errlog.pop();
//             }
            errlog.push(logstr);
            hash[logstr] ++;
        }
    }
    
    //记录多于8个,弹出旧的记录直到剩下8个
    while(!errlog.empty() && errlog.size() > 8) {
        //cout << errlog.front() << " " << hash[errlog.front()] << endl;
        string tmp = errlog.front();
        hash.erase(tmp);
        errlog.pop();
    }
    
    while(!errlog.empty()) {
        cout << errlog.front() << " " << hash[errlog.front()] << endl;
        errlog.pop();
    }
    return 0;
}



发表于 2021-03-24 00:33:51 回复(1)
直接对每行文件的错误数进行计数,然后在输出的时候只输出最新的8条记录即可
from collections import defaultdict

counter = defaultdict(lambda: 0)
while True:
    try:
        content = input().strip().split(' ')
        filename = content[0].split("\\")[-1][-16:]    # 文件名截取最后16个字符
        counter[f"{filename} {content[1]}"] += 1
    except:
        break
for k in list(counter.keys())[-8:]:
    print(f"{k} {counter[k]}")
发表于 2021-03-22 15:33:22 回复(0)
这题还是有坑的,第一次做只记录8个数据循环,如果多于8组数据,前面的数据有可能丢失。最后改了下
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Error{
    public:
    string m_name;   //错误文件名
    int m_line = 0;  //错误所在行
    int num = 1; // 相同错误计数
};

int main() {
    string str;
    int line = 0; //错误所在行
    vector<Error> vec;  // 记录所有错误
    Error temp;
    int count = 0; // 总错误文件数量计数,用于输出最后8个错误
    int flag = 0; //0:与之前文件未重复  , 1:与之前文件重复
    
    while(cin >> str && cin >> line ){
        int index = str.rfind("\\"); //查找 '\'字符位置
        temp.m_name = str.substr(index+1);  //截取文件名
        temp.m_line = line; // 记录错误所在行
        
        // 遍历vector判断是否有重复,如果重复了,flag标记为1
        for(int i = 0; i< count ;i++){
            if(temp.m_name == vec[i].m_name && temp.m_line == vec[i].m_line){ 
                vec[i].num ++;
                flag = 1;
                break;
            }
        }
        //如果没有重复,即flag为0,则记录下来,count++
        if(flag == 0){
            vec.push_back(temp);
            count++;
        }
        flag = 0;
        
    }
    
    //输出分两种,多于8组数据和少于8组数据。如果多于8组,输出最后8组。少于8组全部输出
    if(vec.size()>8){
        for(int i = count - 8 ;i< vec.size();i++){ 
            int lenth = vec[i].m_name.size();
            string name_temp;
            // 如果文件名多于16个字符,截取最后16个。否则记录全部
            if(lenth > 16){
                name_temp = vec[i].m_name.substr(lenth - 16);
            }
            else name_temp = vec[i].m_name;
            //输出
            cout << name_temp<< " "<< vec[i].m_line << " "<< vec[i].num<<endl;
        }
    }
    else{
        for(int i = 0 ;i< vec.size();i++){ 
            int lenth = vec[i].m_name.size();
            string name_temp;
            if(lenth > 16){
                name_temp = vec[i].m_name.substr(lenth - 16);
            }
            else name_temp = vec[i].m_name;
            cout << name_temp<< " "<< vec[i].m_line << " "<< vec[i].num<<endl;
        }
    }

    return 0;
}


发表于 2021-01-22 16:52:02 回复(0)
 这道题的判例是错的,不满足题干中只输出最后出现的八条错误记录要求。最后一个判例中,倒数第6条错误,在第1条出现过,答案并没有第6条错误。
编辑于 2020-10-06 15:49:22 回复(0)
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
//获取净文件名
string getFileName(string path){
    size_t pos = path.rfind('\\');
    return path.substr(pos + 1);
}
//保留净文件名的后16位
string modifyName(string name){
    if(name.size() > 16){
        name = name.substr(name.size() - 16);
    }
    return name;
}
struct ErrRecord
{
    string _file;
    int _lineNo;
    int _count;
    
    ErrRecord(string file, int lineNo):_file(file), _lineNo(lineNo){
        _count = 1;
    }
    // 后续需要进行查找, 所以先定义好两个错误记录什么情况算相等.
    bool operator==(const ErrRecord& ER){
        return (_file == ER._file) && (_lineNo == ER._lineNo);
    }
};
int main(){
    string file;
    int lineNo;
    vector<ErrRecord> vER;
    while(cin >> file >> lineNo){
        ErrRecord ER(getFileName(file), lineNo);
        auto res = find(vER.begin(), vER.end(), ER);
        if(res == vER.end()){
            vER.push_back(ER);
        }
        else{
            ++res->_count;
        }
    }
    int i = 0;
    if(vER.size() > 8){
        i = vER.size() - 8;
    }
    for(; i < vER.size(); ++i){
        cout << modifyName(vER[i]._file) << " " << vER[i]._lineNo << " " << vER[i]._count << endl;
    }
    return 0;
}

编辑于 2020-09-06 16:56:16 回复(0)
这是认真的?
发表于 2020-08-08 16:55:19 回复(2)
import java.util.*;

class Item {

    String fileName;
    String rowNum;
    int order;

    public Item(String fileName, String rowNum, int order){
        this.fileName = fileName;
        this.rowNum = rowNum;
        this.order = order;
    }

    @Override
    public boolean equals(Object item){
        if(!(item instanceof Item))
            return false;
        return ((Item)item).fileName.equals(this.fileName)
                && ((Item)item).rowNum.equals(this.rowNum);
    }

    @Override
    public int hashCode() {
        return Objects.hash(fileName, rowNum);
    }
}

public class Main{

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        Map<Item, Integer> map = new HashMap<>();
        int order = 0;

        while(sc.hasNext()){

            String[] ss = sc.nextLine().trim().split(" ");
            String[] temp = ss[0].split("\\\\");
            ss[0] = temp[temp.length - 1];
            if(ss[0].length() > 16)
                ss[0] = ss[0].substring(ss[0].length() - 16);
            Integer i;
            if((i = map.get(new Item(ss[0], ss[1], order))) != null)
                map.put(new Item(ss[0], ss[1], order), i + 1);
            else
                map.put(new Item(ss[0], ss[1], order), 1);

            order++;
        }

        Set<Item> keys = map.keySet();
        Object[] keyList = keys.toArray();
        Arrays.sort(keyList, (o1, o2) -> ((Item)o1).order - ((Item)o2).order);
        int count = keyList.length >= 8 ? keyList.length - 8 : 0;
        for(; count < keyList.length; count++){
            Item i = (Item)keyList[count];
            System.out.println(i.fileName + " " + i.rowNum + " " + map.get(i));
        }
    }

}

发表于 2020-07-29 16:20:35 回复(0)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

//由于数据比较多,可以定义一个结构体来辅助处理,且需要虫重载 == ,因为后面需要做判断
//将切割后的文件名,和行号,以及数目 按照条件(通过find函数来判断是否重复)进入vector中
//最后输出最后8个记录的信息
using namespace std;

string getfilename(string str)
{
    int index = str.find_last_of("\\");
    string tmp = str.substr(index+1);
    if(tmp.size() > 16)
    tmp = tmp.substr(tmp.size()-16);
    return tmp;
}

struct errorstr
{
    string filename;
    int fileno;
    int count;
    errorstr(string filename,int fileno)
    {
        this->filename = filename;
        this->fileno = fileno;
        this->count = 1;
    }
    bool operator==(const errorstr & a)
    {
        return a.filename == filename && a.fileno == fileno;
    }
        
};

int main()
{
    string str;
    int n;
    vector<errorstr> vec;
    while(cin>>str>>n)
    {
        errorstr er(getfilename(str),n);
        auto res = find(vec.begin(),vec.end(),er);
        if(res == vec.end())
        {
            vec.push_back(er);
        }
        else
            res->count++;
    }
    if(vec.size() > 8)
    {
         for(int i = vec.size()-8;i<vec.size();i++)
        {
            cout << vec[i].filename << " " << vec[i].fileno << " "
                    << vec[i].count << endl;
        }
    }
    else
    {
        for(int i = 0;i<vec.size();i++)
        {
            cout << vec[i].filename << " " << vec[i].fileno << " "
                    << vec[i].count << endl;
        }
    }
 提交观点     return 0;
}

发表于 2020-07-14 12:24:32 回复(0)