0

what would be the most efficient way to sort a file with millions of string inside it?

I know how to do this, if it were a file with millions if Integers in it.

how to modify our approach if it is string? or any new approach?

prashantitis
  • 1,698
  • 19
  • 47

1 Answers1

-2

First load all the file in memory, then use std::sort

You can do something like this:

std::fstream MyFile("MyFile.txt",ios_base::in);
std::vector<std::string>MyStrings;
while(MyFile.eof()==0){
    std::stringstream MyBuffer;
    MyBuffer<<MyFile;
    MyStrings.push_back(MyBuffer.str())
}
std::sort(MyStrings.begin(),MyStrings.end()); //no need for compare function because it exsits for std::string
meneldal
  • 1,609
  • 1
  • 15
  • 29
  • note that since `std::string` isn't unicode aware or anything, the sorting might not be what you want so you might need to provide your own compare function – meneldal Apr 28 '15 at 03:20
  • 1
    You probably shouldn't loop using `eof()`: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Galik Apr 28 '15 at 03:45
  • I think it's fine if you use it this way. I'm not reading the value when I test for the `EOF`. It is updated after reading so I guess I must misunderstand the explanation there – meneldal Apr 28 '15 at 03:52
  • One problem is that you do not test if the read succeeded before using the value. Another problem is I don't understand how you are reading from `MyFile`. – Galik Apr 28 '15 at 03:54
  • Well I assume `MyFile` is a file stream since that's what you would use in C++. I should have precised that. – meneldal Apr 28 '15 at 03:57