题解 | 统计字符串中各字母字符对应的个数
统计字符串中各字母字符对应的个数
https://www.nowcoder.com/practice/ec2a5ab818be4851948d5b0d83a3d8f4
用[]对map进行插入其实不安全
一般只用[]对map进行读。插入用insert
#include <iostream>
// write your code here......
#include <map>
#include <cctype>
using namespace std;
int main() {
char str[100] = {0};
cin.getline(str, sizeof(str));
// write your code here......
std::map<char, int> m;
int num;
for (auto e : str) {
if (isalpha(e)) {
auto it = m.find(e);
if(it == m.end())
m.insert(std::make_pair(e,1));
else
it->second++;
}
}
auto it = m.begin();
while (it != m.end()) {
printf("%c:%d\n", it->first, it->second);
it++;
}
return 0;
}
百度稳定性 387人发布