用c++编写一个程序,将数字从键盘读入int[ ]类型的数组中。你可以假设数组中最多有50个元素。你的程序最多允许输入50个数字。输出为一个两列的列表。第一列列出了不同的数组元素;第二列是每个元素的出现次数。这个列表应该按照第一列元素从大到小的顺序排序。
时间: 2025-01-27 21:14:54 浏览: 33
以下是一个用C++编写的程序,可以实现你描述的功能:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct ElementCount {
int element;
int count;
};
bool compare(const ElementCount& a, const ElementCount& b) {
return a.element > b.element;
}
int main() {
int arr[50];
int n = 0;
cout << "请输入数字(最多50个,输入非数字结束):" << endl;
// 读取输入
while (cin >> arr[n] && n < 50) {
n++;
}
// 统计每个元素的出现次数
vector<ElementCount> counts;
for (int i = 0; i < n; i++) {
bool found = false;
for (auto& ec : counts) {
if (ec.element == arr[i]) {
ec.count++;
found = true;
break;
}
}
if (!found) {
counts.push_back({arr[i], 1});
}
}
// 排序
sort(counts.begin(), counts.end(), compare);
// 输出结果
cout << "元素\t出现次数" << endl;
for (const auto& ec : counts) {
cout << ec.element << "\t" << ec.count << endl;
}
return 0;
}
```
这个程序的工作原理如下:
1. 首先,我们定义了一个结构体 `ElementCount` 来存储元素及其出现次数。
2. `compare` 函数用于比较两个 `ElementCount` 对象,以便我们可以用元素的值从大到小排序。
3. 在 `main` 函数中,我们使用 `cin` 从键盘读取输入,最多读取50个数字。
4. 读取完成后,我们遍历数组,统计每个元素的出现次数。我们使用一个 `vector<ElementCount>` 来存储这些信息。
5. 然后,我们使用 `std::sort` 和 `compare` 函数对 `counts` 向量进行排序。
6. 最后,我们输出结果,第一列是元素的值,第二列是出现次数。
这个程序可以处理任意数量的输入(最多50个),并正确统计每个元素的出现次数,然后按从大到小的顺序输出结果。
阅读全文