c++如何快速统计字符数组中字符的种类
时间: 2024-03-14 19:46:15 浏览: 15
在 C++ 中,可以使用 std::unordered_map 来快速统计字符数组中字符的种类。具体思路是遍历字符数组中的每个字符,使用 std::unordered_map 记录每个字符出现的次数,最后输出每个字符以及它们出现的次数。
以下是示例代码:
```c++
#include <iostream>
#include <unordered_map>
int main() {
char arr[] = "hello world";
std::unordered_map<char, int> charCount;
for(int i = 0; arr[i] != '\0'; i++) {
if(charCount.find(arr[i]) == charCount.end()) {
charCount[arr[i]] = 1;
}
else {
charCount[arr[i]]++;
}
}
for(auto count : charCount) {
std::cout << count.first << " : " << count.second << std::endl;
}
return 0;
}
```
这个代码将统计字符数组 "hello world" 中每个字符出现的次数,并输出结果。在循环中,如果当前字符不存在于 std::unordered_map 中,则将其插入,并将其值设置为 1。否则,将该字符的计数器加 1。最后,使用一个 for 循环遍历 std::unordered_map 并输出每个字符和它们出现的次数。