fork(1) download
  1. #include <iostream>
  2.  
  3. class Histogram
  4. {
  5. private:
  6. int** matrix;
  7. int lines;
  8. void SortMatrix();
  9. public:
  10. Histogram(){ }
  11. Histogram(int elements[], int elementsNr);
  12. Histogram(int** m, int l);
  13. void Print();
  14. };
  15.  
  16. using namespace std;
  17. Histogram::Histogram(int** m, int l)
  18. {
  19. matrix=m;
  20. lines=l;
  21. SortMatrix();
  22. }
  23.  
  24. Histogram::Histogram(int elements[], int elementsNr)
  25. {
  26. lines=0;
  27. //initialize matrix : elementrNr lines and 2 columns
  28. matrix=new int*[elementsNr];
  29. for(int i=0;i<elementsNr;i++)
  30. {
  31. matrix[i]=new int[2];
  32. matrix[i][0]=5;
  33. matrix[i][1]=5;
  34. }
  35. //search each element from the array in the matrix
  36. bool found=false;
  37. for(int i=0;i<elementsNr;i++)
  38. {
  39. found=false;
  40. for(int j=0;j<elementsNr;j++)
  41. {
  42. //the element was found in the matrix ( on the first column )
  43. if(matrix[j][0] == elements[i])
  44. {
  45. matrix[j][1]++;
  46. found=true;
  47. break;
  48. }
  49. }
  50. if(!found)
  51. {
  52. matrix[lines][0]=elements[i];
  53. matrix[lines][1]=1;
  54. lines++;
  55. }
  56. }
  57. SortMatrix();
  58.  
  59. }
  60. void Histogram::SortMatrix()
  61. {
  62. bool flag=true;
  63. int temp1;
  64. int temp2;
  65. int i=0;
  66. for (int i = 0; (i < lines - 1); i++) {
  67.  
  68. for (int o = 0; (o < lines - 1); o++) {
  69.  
  70. if ( matrix[ i ][0] < matrix[ o ][0] ) {
  71.  
  72. temp1 = matrix[ i ][0];
  73. temp2 = matrix[ i ][1];
  74.  
  75. matrix[ i ][0] = matrix[ o ][0];
  76. matrix[ i ][1] = matrix[ o ][1];
  77.  
  78. matrix[ o ][0] = temp1;
  79. matrix[ o ][1] = temp2;
  80.  
  81. }
  82.  
  83. }
  84.  
  85. }
  86. }
  87. void Histogram::Print()
  88. {
  89.  
  90. for(int i=0;i<lines;i++)
  91. {
  92. cout<<matrix[i][0]<<" : " <<matrix[i][1]<<endl;
  93. }
  94.  
  95. }
  96.  
  97. int main() {
  98. int arr[] = {4, 2, 7, 8, 3, 5, 7, 8, 3, 1, 5, 7, 9, 4, 2, 33, 7};
  99. Histogram h(arr, 17);
  100. h.Print();
  101. }
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
1 : 1
2 : 2
3 : 2
4 : 2
7 : 4
8 : 2
9 : 1
33 : 1