我的程序运行时要求用户输入指定的整数,然后在动态数组中存储更多的整数。输出结果给出了一个直方图,它使用星星来显示每个整数中有多少个。
除了一项任务外,我已经完成了所有的任务。我已经尝试了几个小时来实现交换函数,但是找不到解决问题的方法。
我的问题是,我想让我的输出从最少到最大。例如,
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;
}发布于 2016-08-16 01:21:15
您想要的是在计算元素之前对向量进行排序。
void hist(int arr[], int n){
sort(arr, arr+n);
...
}我建议你改变你的解决方案。如果您使用的是std::map,那么您就可以以预先安排好的方式解决问题。另外,你为什么不使用std::vector
https://stackoverflow.com/questions/38965031
复制相似问题