我具有一个功能,其中检查了字符中的字符和次数。
它被存储为(例如)字符串为" Hello" [H] => 1 [E] => 1 [L] => 2 [O] = 1
每当一个字母不止一次地发生时,我都需要更新。
我尝试使用
it->second = it->second+1;
但行不通我该怎么做?
完整代码是
int fn(string a) {
map<char,int> mymap;
for(int i=0;i<a.size();i++)
{
std::map<char, int>::iterator it = mymap.find(i);
if(it!=mymap.end())
{
//say i need to update occurrence from 1 to 2 or 2 to 3...
it->second = it->second+1;//(how can i do that)
}
else
mymap.insert(pair<char,int>(a[i],1));
}
std::map<char,int>::iterator i;
for(i=mymap.begin();i!=mymap.end();i++)
{
cout<<i->first<<i->second;
}
}
您不需要所有这些代码。你可以说
for (auto c : a) mymap[c]++;
这起作用是因为MAP的operator[]
在给定键不存在时插入零初始化元素。