I need to sort a txt file by date, I need to work with the info stored in a vector, then sort it. I made a function that opens the file and stores all the lines in the vector "contents". I’m using visual studio code.
The code I got:
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <vector>
using namespace std;
int readFile(){
ifstream file;
string filename = "searches.txt";
string line;
file.open(filename);
vector<string> contents;
while(!file.eof()){
getline(file, line);
contents.push_back(line);
}
for (auto file_line : contents)
cout << file_line << endl;
file.close();
return 0;
}
int main(){
readFile();
return 0;
};
The actual output looks like this:
Oct 9 10:32:24 423.2.230.77:6166 Failed password for illegal user guest
Aug 28 23:07:49 897.53.984.6:6710 Failed password for root
Aug 4 03:18:56 960.96.3.29:5268 Failed password for admin
Jun 20 13:39:21 118.15.416.57:4486 Failed password for illegal user guest
Jun 2 18:37:41 108.57.27.85:5491 Failed password for illegal user guest
Oct 1 07:22:46 450.25.888.72:5978 Illegal user
Sep 14 10:01:55 694.78.591.36:5537 Failed password for illegal user guest
Jun 16 22:09:01 84.88.502.53:6452 Failed password for illegal user test
Sep 24 17:22:12 311.49.840.89:4145 Failed password for illegal user guest
Jul 12 20:17:38 390.18.339.91:6610 Failed password for root
Jul 16 03:38:22 990.87.715.21:6558 Failed password for admir/
Oct 26 00:53:10 505.13.173.18:4083 Failed password for illegal user guest
How can I sort the vector content by date ?
2
Answers
It is rarely a good (or easy or fast) choice to implement plain text processing (which you need to make the text sortable) in C++. Bash is a much better fit for that purpose. You may still get a C++-like performance thanks to
sort
, not to mention the scalability ofsort
(and its capability to sort inputs larger than RAM).You can use
std::sort
to sort all elements in yourstd::vector<std::string>
.However, by default,
std::sort
will callstd::string::operator<
to determine whether one object is smaller than another. This function will only perform a lexicographical comparison of both strings. This is not what you want. You want the strings to be sorted by the date they contain. In order to preventstd::sort
from usingstd::string::operator<
, you will have to write your own comparison function and tellstd::sort
to use that function instead.Here is an example:
For the input stated in the question, this program has the following output:
However, parsing both lines every time
std::sort
calls the compare function is not very efficient. Therefore, it would be more efficient to parse every line only once, and to cache the parsing results:This second program has the same output as the first program.