Click here to Skip to main content
15,921,660 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C++
  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.
Posted
Updated 14-Nov-15 2:29am
v2

1 solution

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, use map::at(). But note that this will throw en exception if the key does not exist.

Getting the settings you want is much simpler:
C++
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900