【发布时间】: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