A simple example program that uses a set is a spelling checker.
NOTE -- This program can be found in the file spell.cpp.
The checker takes as arguments two input streams: the first represents a stream of correctly spelled words (that is, a dictionary), and the second a text file. To begin, the dictionary is read into a set. This is performed with a std::copy() function and an input stream iterator, copying the values into an inserter for the dictionary. Next, words from the text are examined one by one, to see if they are in the dictionary. If they are not, they are added to a set of misspelled words. After the entire text has been examined, the program outputs the list of misspelled words.
typedef std::set <std::string, std::less<std::string>, std::allocator<std::string> > stringset; typedef std::ostream_iterator<std::string, char, std::char_traits<char> > ostrm_iter; typedef std::istream_iterator<std::string, char, std::char_traits<char>, ptrdiff_t> istrm_iter; void spellCheck (istream& dictionary, istream& text) { stringset words, misspellings; std::string word; istrm_iter eof, dstream (dictionary); // First read the dictionary. std::copy (dstream, eof, std::inserter (words, words.begin ())); // Next read the text. while (text >> word) if (! words.count (word)) misspellings.insert (word); // Finally, output all misspellings. std::cout << std::endl << "Misspelled words:" << std::endl; std::copy (misspellings.begin (), misspellings.end (), ostrm_iter (std::cout, "\n")); }
An improvement would be to suggest alternative words for each misspelling. There are various heuristics that can be used to discover alternatives. The technique we use here is to simply exchange adjacent letters. To find these, a call to the following function is inserted into the loop that displays the misspellings:
{ for (int I = 1; I < word.length(); I++) { std::swap(word[I-1], word[I]); if (words.count(word)) std::cout << "Suggestion: " << word << std::endl; // put word back as before std::swap(word[I-1], word[I]); } }