删除所有具有零值的地图键

ale*_*per 0 c++ dictionary erase

有这个地图,其键属于{0,1,2,3}.

我需要擦除其值等于0的所有键.

这段代码是一个好习惯吗?

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);
Run Code Online (Sandbox Code Playgroud)

它似乎工作但迭代在地图上并在同一循环中擦除键让我感到不舒服.

如果这段代码不是很好的方式,那么在地图中删除零值的所有键的最佳方法是什么?

S.M*_*.M. 6

这是一个非常接近您的任务的好例子http://en.cppreference.com/w/cpp/container/map/erase 我为您更新了它.

#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 << ' ';
}
Run Code Online (Sandbox Code Playgroud)

输出:

1 3 5
Run Code Online (Sandbox Code Playgroud)

我建议您更频繁地访问http://en.cppreference.com.

  • 对于OP中的少量元素来说无关紧要,但这种解决方案可能比原始解决方案更快. (2认同)