Translator Translator::intersection(const Translator &first, const Translator &second){ multimap <string, string> fst_dict = first.dictionary, snd_dict = second.dictionary; multimap <string, string>::iterator fst_it = fst_dict.begin(), fst_end = fst_dict.end(), snd_it, snd_curr_key, snd_end = snd_dict.end(), fst_stop, snd_stop; pair <multimap <string, string>::iterator, multimap<string, string>::iterator> key_range; string origin, mid; set <string> curr_translations; Word curr_entry; Translator intersection; while(fst_it != fst_end){ origin = fst_it->first; snd_curr_key = snd_dict.find(origin); fst_stop = fst_dict.upper_bound(origin); if(snd_curr_key != snd_end){ // the key is on the second translator too curr_translations.clear(); // empty the translations for this key snd_stop = snd_dict.upper_bound(origin); for(; fst_it != fst_stop; ++fst_it){ // iterate over the A->B translations for(snd_it = snd_curr_key; snd_it != snd_stop; ++snd_it){ // iterate over the C->B if(fst_it->second == snd_it->second){ // translations match curr_translations.insert(fst_it->second); } } } if(not curr_translations.empty()){ curr_entry = Word(origin, curr_translations); intersection.addEntry(curr_entry); } } fst_it = fst_stop; } return intersection; }
Translator Translator::compose(const Translator &first, const Translator &second){ multimap <string, string> fst_dict = first.dictionary, snd_dict = second.dictionary; multimap <string, string>::iterator fst_it = fst_dict.begin(), fst_end = fst_dict.end(), snd_it, stop; pair <multimap <string, string>::iterator, multimap<string, string>::iterator> key_range; string origin, mid; set <string> curr_translations; Word curr_entry; Translator composition; while(fst_it != fst_end){ origin = fst_it->first; stop = fst_dict.upper_bound(origin); curr_translations.clear(); // empty the translations for this key for(; fst_it != stop; ++fst_it){ mid = fst_it->second; key_range = snd_dict.equal_range(mid); for(snd_it = key_range.first; snd_it != key_range.second; ++snd_it){ curr_translations.insert(snd_it->second); } } curr_entry = Word(origin, curr_translations); composition.addEntry(curr_entry); } return composition; }