在我的项目中,我想将键插入 map 。所有新键的值应为 1.0,但现有键应增加 1。
这是代码
vector <string> pairs;
map<string, float> two;
map <string, float>::iterator it;
string a = "a";
string b = "b";
string c = "a";
pairs.push_back(a);
pairs.push_back(b);
pairs.push_back(c);
for(int i=0; i<pairs.size(); i++)
{
it = two.find(string(pairs[i]) );
if(i==0)
{
two[string(pairs[i])]=1.0;
}
else if ( it == two.end() )
{
it->second = it->second + 1.0;
//after this line ^,my compiler stop working
}
else
{
two[string(pairs[i])]=1.0;
}
}
在此之后,该对象应该是
a 2
b 1
我该怎么做。
最佳答案
最简单、最有效的解决方案是:
for (auto const& s : pairs) two[s] += 1.0;
这是有效的,因为如果键不存在, map 上的 []
运算符会使用默认值构造函数自动创建一个条目。对于 float ,默认构造函数生成 0.0。
由于 [] 返回一个引用,因此不会进行额外的查找来增加值。
关于c++ - 检查映射中是否存在键然后更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30407449/