在这个的基础上,我想让输出依照从小到大,请修改
时间: 2024-04-08 18:35:35 浏览: 15
好的,你可以稍作修改以按照键(数字)从小到大的顺序输出结果。以下是修改后的代码:
```cpp
#include <iostream>
#include <unordered_map>
#include <vector>
#include <map>
std::map<int, int> countElements(const std::vector<int>& arr) {
std::map<int, int> count;
for (int num : arr) {
count[num]++;
}
return count;
}
int main() {
std::vector<int> arr = {1, 2, 3, 2, 1, 3, 4, 2, 1};
std::map<int, int> result = countElements(arr);
for (const auto& pair : result) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
```
这段代码在原有基础上,将哈希表的类型从`std::unordered_map`修改为`std::map`。`std::map`是一个有序的关联容器,会根据键的大小自动排序。因此,输出结果将按照键(数字)从小到大的顺序进行输出。对于给定的示例输入,输出将为:
```
1: 3
2: 3
3: 2
4: 1
```
这表示数字1出现3次,数字2出现3次,数字3出现2次,数字4出现1次。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)