本文介绍了std :: map :: insert不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一个数字中每个数字的出现次数。

这个想法很简单。我保存了一个地图,其中'digit'为'key','出现次数'为'value'。



但是当插入该对时,它会被插入为零而不是一个。



I am trying to find out count of occurrence of each digit in a number.
The idea is simple. I kept a map with 'digit' as 'key' and 'number of occurrence' as 'value'.

But when the pair is getting inserted, it is inserted as zero instead of one.

  int x = 121123;
  map<int, int> container;
while (x > 0)
{
    int temp = x % 10;
    int b = container[temp];
    if (b > 0)
    {
        container[temp]++;
    }
    else
    {
        container.insert(pair<int, int>(temp, 1)); //value getting inserted as zero instead of one.
    }

    x = x / 10;
}





我不知道发生了什么。为什么将值插入为零。



I have no idea what is going on. Why the value is inserted as zero.

推荐答案

while (x > 0)
{
    int temp = x % 10;
    container[temp]++;
    x = x / 10;
}



如果密钥不存在,则创建值为零,然后递增。如果它已经存在,则只是递增。


If the key does not exist, it is created with value zero and then incremented. If it exists already, it is just incremented.


这篇关于std :: map :: insert不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:58