Search code examples
c++dictionaryerase

Delete all the map keys with zero values


There is this map whose keys belong to the {0, 1, 2, 3}.

I need to erase all the keys whose value equals 0.

Is this code a good practice?

map<int, int> nums = {{0, 1}, {1, 3}, {2, 0}, {3, 1}};

for(int i = 0; i < 4; i++)
    if (nums.count(i) > 0 && nums[i] == 0)
        nums.erase(i);

It seems to work but iterating over the map and erasing the key in the same loop makes me uncomfortable.

If this code is not a good fashion, what is the best way to erase all the keys with zero value in the map?


Solution

  • Here is a good example very close to your task http://en.cppreference.com/w/cpp/container/map/erase I updated it for you.

    #include <map>
    #include <iostream>
    
    int main()
    {
        std::map<int, int> c = {{1, 1}, {2, 0}, {3, 3},
                                        {4, 0}, {5, 5}, {6, 0}};
        // erase all key-value pairs with zero values from c
        for(auto it = c.begin(); it != c.end(); )
            if(it->second == 0)
                it = c.erase(it);
            else
                ++it;
        for(auto& p : c)
            std::cout << p.second << ' ';
    }
    

    Output:

    1 3 5
    

    I recommend you to visit http://en.cppreference.com more often.