Here is an example that assumes that you can sort each file in memory, but cannot merge them in memory. Instead of demonstrating with files, I have chosen to demonstrate with a generous helping of stringstreams.
Code:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
void sortWordList(std::istream& word_list, std::ostream& sorted_word_list);
int main()
{
std::stringstream files[5];
files[0] << "a d e f i j k m r s t y z";
files[1] << "b c g h l n o p q u v w x";
sortWordList(files[0], files[2]);
sortWordList(files[1], files[3]);
std::set_union(
std::istream_iterator<std::string>(files[2]),
std::istream_iterator<std::string>(),
std::istream_iterator<std::string>(files[3]),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(files[4], " "));
std::cout << files[4].str() << std::endl;
}
void sortWordList(std::istream& word_list, std::ostream& sorted_word_list)
{
// Read in the words into memory.
std::vector<std::string> words;
std::copy(
std::istream_iterator<std::string>(word_list),
std::istream_iterator<std::string>(),
std::back_inserter(words));
// Sort the list, remove duplicates and store to the output stream.
std::sort(words.begin(), words.end());
std::copy(words.begin(), std::unique(words.begin(), words.end()),
std::ostream_iterator<std::string>(sorted_word_list, " "));
}
If you cannot sort each individual word list in place, then the solution is to move half of the word list into another file, then use the process outlined above, without using sortWordList() since std::set_union would suffice.
A caveat though: this is based on how I think std::set_union should behave with respect to stream iterators (i.e., it does not keep everything in memory), and I could be wrong.