直方图函数使用动态数组c++ 11
Histogram function using Dynamic arrays C++11
我的程序运行时要求用户输入指定的整数,然后将更多的整数存储在动态数组中。输出给出了一个直方图,用星号表示每个整数的个数。
除了一项任务,我已经完成了所有的任务。我已经尝试了几个小时实现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
呢?
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '