直方图函数使用动态数组c++ 11

Histogram function using Dynamic arrays C++11

本文关键字:数组 c++ 动态 函数 直方图      更新时间:2023-10-16

我的程序运行时要求用户输入指定的整数,然后将更多的整数存储在动态数组中。输出给出了一个直方图,用星号表示每个整数的个数。

除了一项任务,我已经完成了所有的任务。我已经尝试了几个小时实现swap功能,但无法找到解决我问题的方法。

我的问题是我想让我的输出从最小到最大的顺序。例如,

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

但是,我想要下面的输出代替

Histogram: 4 * 10 ** 20 **

下面是我的代码:
#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;
}

你需要的是在计算元素之前对vector进行排序。

void hist(int arr[], int n){
  sort(arr, arr+n);
  ...
}
我建议你改变你的解决方案。如果你使用的是std::map,你的问题的解决方案就在那里,以一种预定的方式。另外,为什么不使用std::vector呢?