KY127 统计字符

又把map忘了…复习一下

#include <bits/stdc++.h>
using namespace std;
int main(){
    string s;
    while(getline(cin,s) && s != "#"){
        string str;
        getline(cin, str);
        map<char, int> mp;
        mp.clear();
        for(auto c : str) mp[c]++;
        //此题只要出现在模式串s中的字符都要输出,哪怕在str串中没有出现
        for(auto c : s) {
         //   if(mp.find(c) != mp.end()){
                cout << c <<" "<<mp[c]<<endl;
       // }
       //加上注释的判断反而不符合题目要求了
    }
    return 0;
}

另外判断map中某个key没有出现还可以这样判断:
使用Count函数,如果返回1则存在,返回0则不存在

if (1 == mp.count(key)){
	//mp中有键key
}else{
	//mp中没有键key
}
Logo

云原生社区为您提供最前沿的新闻资讯和知识内容

更多推荐