David Ha David Ha - 3 months ago 25
C++ Question

Histogram function using Dynamic arrays C++11

My program runs to ask for user input of a specified integer followed by storing more integers in a dynamic array. The output gives out a histogram uses stars to show how many of each integer.

I have every task completed except for one. I have tried implementing a swap function for hours but could not figure out a solution to my problem.

My problem is that I want to get my output in order from least to greatest.
For example,

Enter number of grades:
5
Enter grades (each on a new line):
20
4
10
10
20
Histogram:
20 **
4 *
10 **


However, I want the following output instead

Histogram:
4 *
10 **
20 **


Here is my code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>

using namespace std;

void hist(int arr[], int n);

void swap(int &a, int &b);

int main(){
int* arr = NULL;
int number;
cout << "Enter number of grades:" << endl;
cin >> number;

cout << "Enter grades (each on a new line):" << endl;
arr = new int[number];
for(int i = 0; i < number; i++){
cin >> arr[i];
}
hist(arr, number);
return 0;
delete [] arr;
}

void hist(int arr[], int n){
cout << "Histogram:" << endl;
for (int i = 0; i < n; i++){
int j;
for (j = 0; j < i; j++)
if(arr[i] == arr[j])
break;
if (i == j){
int xx = count(arr, arr+n, arr[i]);
cout << setw(3) << arr[i] << " ";
for (int j = 0; j < xx; ++j){
cout << "*";
}
cout << endl;
}
}
}

void swap(int &a, int &b){
int temp;
temp = a;
a = b;
b = temp;
}

Answer

What you want is to sort the vector before counting the elements.

void hist(int arr[], int n){
  sort(arr, arr+n);
  ...
}

I would suggest you to change your solution. If you were using a std::map you would have the solution of your problem right there, in a preordered fashion. Also, why don't you use a std::vector?

Comments