You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中基于日期对vector存储的TXT文件内容排序?

按日期排序日志文件内容的实现方案

首先修正你现有代码中的文件读取问题:while(!file.eof()) 会导致程序多读一行空内容,改为 while(getline(file, line)) 可以避免这个问题。

要实现按日期排序,核心是给std::sort提供自定义的比较规则,具体步骤如下:

1. 建立月份缩写与数字的映射

日志中的月份是英文缩写,需要将其转换为1-12的数字,方便数值比较。我们可以用unordered_map来实现这个映射。

2. 编写日期解析与比较逻辑

从每行日志中提取月份、日期、时间信息,将其转换为一个可直接比较的数值(比如组合成一个长整数),然后通过比较数值大小判断日期的先后顺序。

3. 调用std::sort完成排序

读取完所有日志行后,调用std::sort并传入自定义的比较函数,即可完成按日期排序。

修改后的完整代码

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <sstream>
#include <cstdio>
using namespace std;

// 月份缩写到数字的映射表
const unordered_map<string, int> monthMap = {
    {"Jan", 1}, {"Feb", 2}, {"Mar", 3}, {"Apr", 4},
    {"May", 5}, {"Jun", 6}, {"Jul", 7}, {"Aug", 8},
    {"Sep", 9}, {"Oct", 10}, {"Nov", 11}, {"Dec", 12}
};

// 将日志行的日期时间转换为可比较的长整数值
long long getTimeValue(const string& line) {
    istringstream iss(line);
    string monthStr, timeStr;
    int day, hour, minute, second;

    // 提取日志行的前三个字段:月份、日期、时间
    iss >> monthStr >> day >> timeStr;
    // 分割时间字符串为小时、分钟、秒
    sscanf(timeStr.c_str(), "%d:%d:%d", &hour, &minute, &second);

    int month = monthMap.at(monthStr);
    // 计算时间总秒数
    int totalSeconds = hour * 3600 + minute * 60 + second;
    // 组合成唯一的数值:月*100000000 + 日*1000000 + 总秒数,确保数值越大日期越晚
    return (long long)month * 100000000LL + (long long)day * 1000000LL + totalSeconds;
}

// 自定义比较函数:按日期从早到晚排序
bool compareByDate(const string& a, const string& b) {
    return getTimeValue(a) < getTimeValue(b);
}

int readFile(){
    ifstream file;
    string filename = "searches.txt";
    string line;

    file.open(filename);
    // 增加文件打开失败的判断
    if (!file.is_open()) {
        cerr << "无法打开目标文件" << endl;
        return -1;
    }

    vector<string> contents;

    // 修正读取逻辑,避免多读空行
    while(getline(file, line)){
        contents.push_back(line);
    }

    // 执行按日期排序
    sort(contents.begin(), contents.end(), compareByDate);

    // 输出排序后的日志内容
    for (const auto& file_line : contents)
        cout << file_line << endl;
 
    file.close();
    return 0;
}

int main(){
    readFile();
    return 0;
};

关键代码说明

  • monthMap:快速将英文月份缩写转换为数字,解决月份字符串无法直接比较的问题。
  • getTimeValue:解析日志行的日期时间信息,将其转换为一个长整数,数值大小直接对应日期的早晚,简化比较逻辑。
  • compareByDate:作为std::sort的排序规则,告知排序算法如何判断两行日志的先后顺序。
  • 文件读取修正:使用while(getline(file, line))确保只读取有效行,避免空行或重复行。

内容的提问来源于stack exchange,提问作者Diego Michel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:37:52