我正在尝试读取一个包含 200 行的文本文件,类似于以下四个示例:
1 4:48:08 Orvar Steingrimsson 1979 30 - 39 ara IS200
2 4:52:25 Gudni Pall Palsson 1987 18 - 29 ara IS870
3 5:14:24 Ryan Paavola 1984 18 - 29 ara USA
4 5:18:43 Hendrik Sporing 1990 18 - 29 ara GER
目前,这些行是按他们的时间组织的,如您所见,但我希望按每个参赛者的出生年份来组织它们,这样在这种情况下,这四行将如下所示:
4 5:18:43 Hendrik Sporing 1990 18 - 29 ara GER
2 4:52:25 Gudni Pall Palsson 1987 18 - 29 ara IS870
3 5:14:24 Ryan Paavola 1984 18 - 29 ara USA
1 4:48:08 Orvar Steingrimsson 1979 30 - 39 ara IS200
我应该根据出生年份重新排列行,输入文件是“laugavegurinn.txt”,输出文件是“laugavegurinn2.txt”
谁能指出我的代码的问题和/或提出更好的方法来做到这一点?注意,对 C++ 不是很熟练,希望能得到任何帮助。这是我的代码:
#include <iostream> //for basic functions
#include <fstream> //for basic file operations
#include <string> //for string operations
#include <map> //for multimap functions
using namespace std;
void process (istream &in, ostream &out) {
multimap<int, string> data_by_year;
string str;
while (getline(in,str)) {
int year = stoi(str.substr(54, 4));
data_by_year.insert(make_pair(year, str));
}
for (auto v : data_by_year) {
out << v.second << "\n";
}
}
int main () {
ifstream in;
ofstream out;
in.open("laugavegurinn.txt");
out.open("laugavegurinn2.txt");
process(in, out);
}