fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <utility>
  4. #include <vector>
  5.  
  6. void count(std::vector<int> arr){
  7. std::sort(arr.begin(), arr.end());
  8. int frequency = 1;
  9.  
  10. for (int x =0; x < arr.size()-1; x ++){
  11. if(arr[x]==arr[x+1]){
  12. frequency ++;
  13. }
  14. else{
  15. std::cout << arr[x] << ": " << frequency << std::endl;
  16. frequency = 1;
  17. }
  18. }
  19. }
  20.  
  21. void print_frequencies(std::vector<int> v)
  22. {
  23. std::sort(v.begin(), v.end());
  24.  
  25. if (!v.empty())
  26. {
  27. auto prev = v.front();
  28. std::size_t freq = 1;
  29.  
  30. auto out = [&]{ std::cout << prev << ": " << freq << '\n' ;};
  31.  
  32. for (std::size_t i = 1; i<v.size(); ++i)
  33. {
  34. if (prev == v[i])
  35. ++freq;
  36. else
  37. {
  38. out() ;
  39. prev = v[i];
  40. freq = 1;
  41. }
  42. }
  43. out();
  44. }
  45. }
  46.  
  47. template <typename container_t>
  48. void print(const container_t& c)
  49. {
  50. std::cout << "{ ";
  51.  
  52. for (auto& e: c)
  53. std::cout << e << " " ;
  54.  
  55. std::cout << "}\n";
  56. }
  57.  
  58. int main()
  59. {
  60. std::vector<int> a ;
  61. print(a);
  62. print_frequencies({});
  63.  
  64. std::vector<int> b = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };
  65. print(b);
  66. print_frequencies(b);
  67.  
  68. std::vector<int> c = {1, 2, 1, 3, 1, 3, 5, 1, 5, 1, 5, 1, 4, 1, 4, 1, 8};
  69. print(c);
  70. print_frequencies(c);
  71. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
{ }
{ 1 3 5 7 9 2 4 6 8 10 }
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
7: 1
8: 1
9: 1
10: 1
{ 1 2 1 3 1 3 5 1 5 1 5 1 4 1 4 1 8 }
1: 8
2: 1
3: 2
4: 2
5: 3
8: 1