用c++实现输入一个只包含小写英文字母和数字的字符串,按照不同字符统计个数由多到少输出统计结果,如果统计的个数相同,则按照ASCII码由小到大排序输出。
时间: 2024-10-10 20:11:47 浏览: 76
在C++中,你可以通过使用`std::map`来存储每个字符及其出现次数,同时维护一个`std::vector<std::pair<char, int>>`来辅助按ASCII码排序。下面是基本的步骤:
```cpp
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
void countAndSort(std::string str) {
std::map<char, int> charCount;
for (char c : str) {
if (isalnum(c)) { // 检查是否为字母或数字
charCount[c]++;
}
}
std::vector<std::pair<char, int>> sortedChars(charCount.begin(), charCount.end());
std::sort(sortedChars.begin(), sortedChars.end(),
[](const auto& a, const auto& b) { // 自定义比较函数,先按计数降序,然后按ASCII升序
return a.second > b.second || (a.second == b.second && a.first < b.first);
});
for (const auto& pair : sortedChars) {
std::cout << "Character '" << pair.first << "' appears " << pair.second << " times.\n";
}
}
int main() {
std::string input = "exampleString1234abcde"; // 输入示例
countAndSort(input);
return 0;
}
```
在这个程序中,我们首先遍历字符串并更新字符计数。然后,我们将计数映射转换成一个`std::vector`,并自定义排序函数,以便于满足题目要求的排序规则。最后,我们遍历这个有序的向量并打印出统计结果。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)