题解 | 日志排序
#include <bits/stdc++.h>
using namespace std;
struct Net {
string body;
string timestamp; // 添加时间戳字段
double duration; // 添加消耗时间字段
// 自定义排序逻辑
bool operator<(const Net &a) const {
if (duration == a.duration) {
return timestamp < a.timestamp; // 按时间戳从小到大排序
}
return duration < a.duration; // 按消耗时间从小到大排序
}
Net(string body, string timestamp, double duration)
: body(body), timestamp(timestamp), duration(duration) {}
};
int main() {
string s;
vector<Net> ans;
while (getline(cin, s)) {
// 找最后一个空格
int tag = 0;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == ' ') {
tag = i;
break;
}
}
string c = s.substr(tag + 1); // 提取字段
// 提取时间戳部分(从第一个空格到倒数第二个空格之间的部分)
int first_space = s.find(' ');
int second_last_space = s.find_last_of(' ', tag - 1);
string timestamp = s.substr(first_space + 1, second_last_space - first_space - 1);
// 提取消耗时间部分(最后部分去掉括号和单位)
string duration_str = c.substr(0, c.size() - 3); // 去掉 "(s)"
double duration = stod(duration_str);
// 创建 Net 实例并加入向量
Net a(s, timestamp, duration);
ans.push_back(a);
}
// 按自定义逻辑排序
sort(ans.begin(), ans.end());
// 输出排序结果
for (const auto &a : ans) {
cout << a.body << endl;
}
return 0;
}
看似写的复杂,其实思路很简单,主要是实现一下结构体sort函数,这个问题要求是需要优先按照时间进行排序,然后按照日期进行排序,后者时间实现的方法有很多,如果同学们不会我的这个函数,可以尝试拆分成两个int,进行比较也是可以的,然后就是前面的时间的排序,这个排序的特征是长度一致,直接采用string的比较即可,我这里甚至拿了很多空格,一样可以解决,因为中间一定会出现结果

