1042 字符统计 (20 point(s))
#include <bits/stdc++.h>
using namespace std;
int main() {
// 找出出现最多字母 不包括乱七八糟的符号
map<char, int> alpha;
string str;
// 整行读取字符串
getline(cin, str);
// 统计不区分大小写
for(int i = 0; i < str.size(); i++)
if(isalpha(tolower(str[i])))
alpha[tolower(str[i])]++;
int Max = 0;
auto it = alpha.begin();
for(auto a = alpha.begin(); a != end(alpha); a++){
if(a->second > Max){
Max = a->second;
it = a;
}
}
// 输出小写字母
cout << it->first << " " << it->second;
}
原来 map 是不能用 max_element 这个函数的,用了下好像不对。只能够用循环的方式手动找一遍。
然后找的时候有一个地方,本来开始的时候是用的foreach,但是发现用foreach好像不能将其迭代器的地址赋值给另外的迭代器。所以只能改成普通的for循环。
参考方法用的是在读取的时候求出最大的max。然后再循环一边找出最大对象,直接输出。
而求出最大max方法是,每读取一个字符的时候将对应的val的值判断一次,如果有更大的则覆盖当前的max。
原来max这个变量名在没有是用 max() 比较两个元素大小的函数的时候是可以使用的。
浙公网安备 33010602011771号