fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4.  
  5. struct char_counter
  6. {
  7. char_counter( char first = 'a', char last = 'z' ) : first(first), last(last)
  8. { if( first <= last ) amounts.resize(last-first+1) ; }
  9.  
  10. char_counter& operator << ( char c )
  11. { if( c >= first && c <= last ) ++amounts[c-first] ; return *this ; }
  12.  
  13. char_counter& operator << ( const char* p )
  14. { for( ; *p != 0 ; ++p ) operator<< (*p) ; return *this ; }
  15.  
  16. char_counter& operator << ( const std::string& str )
  17. { for( char c : str ) operator<< (c) ; return *this ; }
  18.  
  19. std::vector<int> amounts ;
  20. const char first ;
  21. const char last ;
  22. };
  23.  
  24. std::ostream& operator<< ( std::ostream& stm, const char_counter& counter )
  25. {
  26. stm << "counts [" << counter.first << '-' << counter.last << "]: { " ;
  27. for( std::size_t i = 0 ; i < counter.amounts.size() ; ++i )
  28. {
  29. int cnt = counter.amounts[i] ;
  30. if( cnt > 0 ) stm << char( i + counter.first ) << ':' << cnt << ' ' ;
  31. }
  32. return stm << '}' ;
  33. }
  34.  
  35. int main()
  36. {
  37. char_counter counter ;
  38. counter << 'a' << "abcde" << std::string("defg") << 'f' << "a?c?d?e?g?x" ;
  39. std::cout << counter << '\n' ;
  40. }
  41.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
counts [a-z]: { a:3 b:1 c:2 d:3 e:3 f:2 g:2 x:1 }