MineSweeper MineSweeper - 1 year ago 76
C++ Question

Linewise lexicographic sort of a file with a catch

Although I am not happy with the title of this question and this might be an odd question; bear with me, please.

So I have text files with content as follows:

& AAABBAB
this
& AAAAAAB
is
& BCAAAA
an
& BBBBBA
example
& BABABAB
text


where every other line starts with an identifier ('&'). Lines with said identifier should be lexicographically sorted, but I need it in a way such that the next line is dragged along to the new position in the output file with it.

This is what I am hoping to be the content of the output file.

& AAAAAAB
is
& AAABBAB
this
& BABABAB
text
& BBBBBA
example
& BCAAAA
an


With this, I can get the file content line-by-line:

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
ifstream is("test.txt");
string str;
while(getline(is, str))
{
cout<<str<<endl;
}
return 0;
}


Is there an easy way to accomplish what I am looking for? Thanks for your help!

Answer Source

I'd bundle the pairs together while reading, making them easy to sort:

vector<pair<string, string>> vec; // first is identifier
vec.reserve(1000);

bool first = true;
while(getline(is, str))
{
    if (first)
        vec.emplace_back(str, string());
    else
        vec.back().second = str;
    first = !first;
}

sort(vec.begin(), vec.end());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download