fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <map>
  5. #include <cctype>
  6. #include <algorithm>
  7.  
  8. std::string make_key( std::string str )
  9. {
  10. // remove non-alphabets
  11. static const auto is_not_alpha = [] ( char c ) { return !std::isalpha(c) ; } ;
  12. str.erase( std::remove_if( str.begin(), str.end(), is_not_alpha ), str.end() ) ;
  13.  
  14. // convert to lower case
  15. for( char& c : str ) c = std::tolower(c) ;
  16.  
  17. // and sort
  18. std::sort( str.begin(), str.end() ) ;
  19.  
  20. return str ;
  21. }
  22.  
  23. using anagram_map = std::map< std::string, std::vector<std::string> > ;
  24.  
  25. anagram_map make_anagram_map( std::istream& stm )
  26. {
  27. anagram_map ana_map ;
  28.  
  29. std::string word ;
  30. while( stm >> word ) ana_map[ make_key(word) ].push_back(word) ;
  31.  
  32. return ana_map ;
  33. }
  34.  
  35. void look_up( const std::string& word, const anagram_map& ana_map )
  36. {
  37. auto iter = ana_map.find( make_key(word) ) ;
  38. if( iter != ana_map.end() )
  39. {
  40. std::cout << "anagrams of '" << word << "':\n" ;
  41. for( const auto& str : iter->second ) std::cout << " " << str << '\n' ;
  42. }
  43. else std::cout << "no anagrams of '" << word << "' were found\n" ;
  44. }
  45.  
  46. #include <sstream>
  47.  
  48. int main()
  49. {
  50. std::istringstream stm( "Petal Maple Teal leapt!! Lepta tale Pleat ample LATE? Plate" ) ;
  51. const anagram_map ana_map = make_anagram_map(stm) ;
  52.  
  53. look_up( "petal", ana_map ) ;
  54. look_up( "late", ana_map ) ;
  55. look_up( "quick", ana_map ) ;
  56. }
  57.  
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
anagrams of 'petal':
    Petal
    leapt!!
    Lepta
    Pleat
    Plate
anagrams of 'late':
    Teal
    tale
    LATE?
no anagrams of 'quick' were found