Advertisement
ToastyStoemp

Anagram

Sep 2nd, 2015
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <fstream>
  5. #include <string>
  6. #include <set>
  7. #include <map>
  8.  
  9. typedef std::vector<std::string> VStr;
  10. typedef std::multimap<std::string, std::string> MStr;
  11.  
  12.  
  13. std::string WordSort(std::string word)
  14. {
  15.     std::sort(word.begin(), word.end());
  16.     return word;
  17. }
  18.  
  19.  
  20. int main()
  21. {
  22.     std::ifstream stream("words.txt");
  23.     VStr all;
  24.     std::string line;
  25.  
  26.     while (std::getline(stream, line))
  27.     {
  28.         all.push_back(line);
  29.     }
  30.  
  31.     std::cout << "----- Anagram List -----" << std::endl << std::endl;
  32.     VStr anagramWords;
  33.     MStr sortedWords;
  34.  
  35.     //creation of the multimap with sorted words, will be used to check for the existance of anagrams
  36.     for (VStr::iterator it = all.begin(); it != all.end(); ++it)
  37.     {
  38.         std::string value = *it;
  39.         std::string key = WordSort(value);
  40.         sortedWords.insert ( std::pair<std::string, std::string>(key, value));
  41.     }
  42.  
  43.     //checking for anagrams
  44.     for (VStr::iterator it = all.begin(); it != all.end(); ++it)
  45.     {
  46.         std::string searchFor = *it;
  47.         searchFor = WordSort(searchFor);
  48.         if (sortedWords.count(searchFor) > 1)
  49.         {
  50.             std::pair <std::multimap<std::string, std::string>::iterator, std::multimap<std::string, std::string>::iterator> ref;
  51.             ref = sortedWords.equal_range(searchFor);
  52.             for (MStr::iterator tick = ref.first; tick != ref.second; ++tick)
  53.             {
  54.                 std::cout << ' ' << tick->second << std::endl;
  55.             }
  56.             MStr::iterator id = sortedWords.find(searchFor);
  57.             std::cout << "\n";
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement