0

I'm having an issue trying to sort a vector of files by their last write time. Sorting seems to work as intended, however sometimes even though the time string shows a higher date, the time_t is lower.

Example Output:

Wed Aug 19 01:51:07 2020 || 1597819867
Wed Aug 19 05:17:20 2020 || 1597832240
Tue Aug 18 18:54:26 2020 || 1597794866
Tue Aug 18 18:43:20 2020 || 1597794200
Tue Aug 18 18:42:38 2020 || 1597794158
Wed Aug 19 22:52:44 2020 || 1597895564 <-Wrong
Thu Aug 13 18:25:32 2020 || 1597361132 <-Wrong
Wed Aug 12 22:36:51 2020 || 1597289811 <-Wrong
Mon Aug 17 21:49:45 2020 || 1597718985

My Code:

for (int i = 0; i < 200; i++) {
    auto diff = GetFileWriteTime(pth) - GetFileWriteTime(dates[i]);
    if (diff > 0.0) {
        itPos = dates.begin();
        if (i > 0) { itPos = dates.begin() + i - 1; }
            dates.insert(itPos, pth);
            dates.pop_back();
            break;
        }
    }
}
  • 1
    I'd suggest using `std::sort` then you only need a easy compare for file write time. – Louis Go Aug 20 '20 at 07:15
  • 1
    This doesn't look like a sort function to me. – n. m. could be an AI Aug 20 '20 at 07:25
  • 4
    Please provide [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) if you want your algorithm to be resolved. – Louis Go Aug 20 '20 at 07:27
  • Your example output is not sorted at all; it goes up and down seemingly randomly. It's not limited to the three marked lines. I also don't see any instance of "the time string shows a higher date, the time_t is lower" - as far as I can tell, the two halves of each line are matching. – Igor Tandetnik Aug 22 '20 at 14:32
  • Off the top, `itPos` ends up being the same (namely, `dates.begin()` ) for both `i == 0` and `i == 1`. That doesn't look right. – Igor Tandetnik Aug 22 '20 at 14:34

0 Answers0