by JanneVee · 13y ago · 0 comments
#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/clingIt'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.