【问题标题】:Histogram function using Dynamic arrays C++11使用动态数组 C++11 的直方图函数
【发布时间】:2016-08-16 00:44:54
【问题描述】:

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

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

我的问题是我想按从小到大的顺序排列我的输出。 例如,

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;
}

【问题讨论】:

  • std::swap。你是using namespace std;,所以你要添加到std::swaps 重载集。您是否尝试过从一个更简单的函数调用您的交换函数,以查看这是否是真正给您带来问题的原因?也停止这样做:int x; x = 1; 并只是做int x = 1;

标签: c++ c++11 histogram dynamic-arrays


【解决方案1】:

你想要的是在计算元素之前对向量进行排序。

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

我建议您更改解决方案。如果您使用的是std::map,那么您就可以以预先订购的方式解决您的问题。 另外,你为什么不使用std::vector

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-09
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多