fork download
  1. #include <iostream>
  2. #include <vector>
  3. // using namespace std; // *** avoid
  4.  
  5. /*void*/ int main() // *** main must return int
  6. {
  7. const int a[] = { 1, 2, 2, -2, 2, -2, 3, -2, 3, -3, -2 };
  8. const int N = sizeof(a) / sizeof( a[0] ) ;
  9.  
  10. // find the smallest and biggest elements
  11. int smallest = a[0] ;
  12. int biggest = a[0] ;
  13. for( int i = 1 ; i < N ; ++i )
  14. {
  15. if( a[i] < smallest ) smallest = a[i] ;
  16. if( a[i] > biggest ) biggest = a[i] ;
  17. }
  18.  
  19. // we can't use a c-style array for f; size is not known at compile time
  20. // http://w...content-available-to-author-only...a.com/tutorials/vectors.html
  21. std::vector<int> f( (biggest-smallest) + 1 ) ;
  22. for( int i = 0 ; i < N ; ++i ) ++f[ a[i] - smallest ] ;
  23.  
  24. for( std::size_t i = 0 ; i < f.size() ; ++i )
  25. {
  26. const int count = f[i] ;
  27. if( count > 0 )
  28. {
  29. const int n = i + smallest ;
  30. std::cout << n << " appears " << count << " time" ;
  31. if( count > 1 ) std::cout << 's' ;
  32. std::cout << ".\n" ;
  33. }
  34. }
  35. }
  36.  
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
-3 appears 1 time.
-2 appears 4 times.
1 appears 1 time.
2 appears 3 times.
3 appears 2 times.