std :: map :: insert不起作用 [英] std::map::insert is not working
本文介绍了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.
推荐答案
这是因为 map :: operator [] [ ^ ]当键到目前为止不存在时插入一个新元素并将值设置为零。因此,下面调用 map :: insert() [ ^ ]将始终失败。
如果您想获得没有自动插入的值,请使用map :: at()
。但请注意,如果密钥不存在,这将抛出异常。
获得您想要的设置要简单得多:
This is because the map::operator [][^] is inserting a new element when the key does not exist so far and sets the value to zero. As a result the follwing call to map::insert()[^] will always fail.
If you want to get a value without automatic insert, usemap::at()
. But note that this will throw en exception if the key does not exist.
Getting the settings you want is much simpler:
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不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文