fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <deque>
  4. #include <string>
  5. #include <algorithm>
  6.  
  7. int main()
  8. {
  9. const std::string my_strings[] =
  10. {
  11. "thing1", "abcd", "accc", "super",
  12. "consider", "using", "the", "standard", "library",
  13. "it", "makes", "life", "a", "lot", "easier"
  14. };
  15.  
  16. // http://w...content-available-to-author-only...s.com/reference/map/map/
  17. // http://w...content-available-to-author-only...s.com/reference/deque/deque/
  18. std::map< char, std::deque<std::string> > dict ;
  19.  
  20. // add the strings to the dictionary in any order
  21. // http://w...content-available-to-author-only...p.com/C++11FAQ.html#for
  22. for( const std::string& str : my_strings )
  23. if( !str.empty() ) dict[ str[0] ].push_back(str) ;
  24.  
  25. // http://w...content-available-to-author-only...p.com/C++11FAQ.html#auto
  26. for( auto& pair : dict ) // sort strings under each alphabet
  27. {
  28. auto& deque = pair.second ;
  29. // http://w...content-available-to-author-only...s.com/reference/algorithm/sort/
  30. std::sort( std::begin(deque), std::end(deque) ) ;
  31. }
  32.  
  33. for( const auto& pair : dict ) // print out the contemts
  34. {
  35. std::cout << "key: '" << pair.first << "' values: [ " ;
  36. for( const std::string& str : pair.second )
  37. std::cout << "'" << str << "' " ;
  38. std::cout << "]\n" ;
  39. }
  40. }
Success #stdin #stdout 0s 3440KB
stdin
Standard input is empty
stdout
key: 'a'  values: [ 'a' 'abcd' 'accc' ]
key: 'c'  values: [ 'consider' ]
key: 'e'  values: [ 'easier' ]
key: 'i'  values: [ 'it' ]
key: 'l'  values: [ 'library' 'life' 'lot' ]
key: 'm'  values: [ 'makes' ]
key: 's'  values: [ 'standard' 'super' ]
key: 't'  values: [ 'the' 'thing1' ]
key: 'u'  values: [ 'using' ]