This code will read in the names of two files, open the first file, read all the words in it, sort them alphabetically, remove duplicates, and write it to the second file.
int main()
{
string from, to;
// Read input filenames
cin >> from >> to;
// Open the input file as an ifstream
ifstream is(from.c_str());
// Get a string iterator over input file
istream_iterator ii(is);
// The default istream_iterator indicates EOF
istream_iterator eos;
// Read each word of the file into the vector
vector b(ii, eos);
// Sort all the words
sort(b.begin(), b.end());
// Open output file
ofstream os(to.c_str());
// Create an output iterator for the file, which will write a "\n" each time along
// with the string
ostream_iterator oo(os, "\n");
// Copy the vector into the file, skip dups
unique_copy(b.begin(), b.end(), oo);
// Error code - return 0 for successful completion
return( !is.eof() || !os);
}
This is truly a brilliant demonstration of abstraction. By creating iterators to deal with the input and output files, we can use the C++ standard library algorithms to do a variety of useful things. Truly beautiful.
No comments:
Post a Comment