4 ms·
How about #include <iostream> #include <iterator> #include <algorithm> #include <fstream> #include <string> #include <vector> usin
by JanneVee 13y ago
How about
#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Line
{
string lineData;
operator string() const
{
return lineData;
}
};
std::istream& operator>>(std::istream& str,Line& data)
{
getline(str,data.lineData);
return str;
}
int main(int argc, const char * argv[])
{
ifstream ifile(argv[1]);
ofstream ofile(argv[2]);
vector<string> data;
copy(istream_iterator<Line>(ifile), istream_iterator<Line>(), back_inserter(data));
sort(data.begin(), data.end());
copy(data.begin(),data.end(), ostream_iterator<string>(ofile, "\n"));
return 0;
}
And to inform everyone. Cling as a C++ REPL exists. http://root.cern.ch/drupal/content/cling http://root.cern.ch/drupal/content/cling
- pmelendez 13y agoYou are including way more lines of code... I don't get your point... sorry :(
- JanneVee 13y agoI eliminated the loops and did the processing with STL algorithms and iterators. It is ugly as sin if you try to process lines like the original code. Most scripting languages do rather well with lines but C++ does not.
- abelsson 13y agoHah, I was just about to post more or less exactly the same code. :) It's funny, had the author tweaked the problem just slightly to try make C++ look good by saying that the program should output sorted words instead of lines, you could have deleted the entire Line nonsense. Had the problem been to output sorted, unique words, you could have made the rather elegant: int main(int argc, const char* argv[]) { using input = istream_iterator<string>; using output = ostream_iterator<string>; ifstream inputfile(argv[1]); ofstream outputfile(argv[2]); set<string> words{input(inputfile), input()}; copy(words.begin(), words.end(), output(outputfile, "\n")); } But then again, it's not exactly in C++'s favor as a scripting language that copying words is easy, while lines is hard.
- JanneVee 13y agoYeah, it is not a scripting language for processing lines. Although the line nonsense has a benefit though it could be adapted to parse out records and by overloading the less than operator to sort on a specific column. But then you would might use AWK instead.