- string的添加用+就可以了,insert是两个参数,一个pos(要用迭代器),一个是插入的元素
- 之前的代码有一个bug最后一个单词不会读入,因为没有碰到其他字符 比如只有一个 A时,A不会读入
#include <cstdio>
#include <string>
#include <iostream>
#include <map>
using namespace std;
//被非字母数字分割开的所有
int main()
{
map<string, int> words;
string line;
getline(cin,line);
string word;
for(string::iterator it=line.begin();it!=line.end();it++){
if((*it>='a'&&*it<='z')||(*it>='A'&&*it<='Z')||(*it>='0'&&*it<='9')){
if(*it>='A'&&*it<='Z'){
*it='a'+(*it-'A');
}
word.insert(word.end(),*it);
}
else if(!word.empty()){
words[word]++;
word.clear();
}
}
if(!word.empty())words[word]++;
int ma=0;
string tmp;
/*for(map<string,int>::iterator it=words.begin();it!=words.end();it++){
tmp = it->first;
cout<<tmp<<" "<< it->second<<endl;
}*/
for(map<string,int>::iterator it=words.begin();it!=words.end();it++){
if(it->second > ma){
ma=it->second;
tmp=it->first;
}
}
cout<<tmp<<" "<<ma<<endl;
return 0;
}
- 可以像书上写得那样,如果碰到单词,则一次性读完,读完后直接存入MAP;而不用一个一个读,读到非法字符在存入;
- 同理读到非法单词后,则一次性读完所有非凡的字符