c++ - 检查映射中是否存在键然后更新值

标签 c++ dictionary

在我的项目中,我想将键插入 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/

相关文章:

javascript - Angular 10 - Openlayers 获取 map 坐标(点击)

python - 比较嵌套字典和列表中的值

c++ - 软件控制程序

c++ - R 值引用和 std::make_unique

c++ - 远近不一致

java - 如何对Map of Map使用双括号初始化

C# 图像识别性能——比较图像列表和图像字典

python - 如何从Python中具有多个元素的字典中获取最大值

c++ - 从函数返回 shared_ptr 的取消引用值

带有 if 语句的 C++ 字符串变量