c++ - 在map删除C++期间循环执行了多少次

标签 c++ dictionary erase

void main() {
        map<int, int> m;
        m[1] = 1;
        m[2] = 1;
        for (auto it : m) {
            cout<<"current: "<<it.first<<endl;
            m.erase(1);
            m.erase(2);
        }
    }

猜猜这个循环执行了多少次?是 2!

但是,如果我删除“m.erase(1)”,循环就会执行一次。

我很困惑为什么循环执行两次?

最佳答案

std::map::erase将使被删除元素的迭代器无效。之后,无效的迭代器用于 for range 循环中的增量操作,这会调用未定义的行为。所以你基本上无法知道它执行循环的次数。

正确的代码片段如下:

for(auto it = m.begin(); it != m.end(); )
        if( /*condition */ )
            it = m.erase(it);
        else
            ++it;

关于c++ - 在map删除C++期间循环执行了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53027665/

相关文章:

c++ - c++ 中的 .erase() 问题

c# - 如何删除位图上的内容

c++ - 为什么从函数调用时 c++11 std::normal_distribution 返回相同的模式?

c++ - 如何删除 vector 中的元素(或 A 和 B 之间的距离)

c++ - 使用模式初始化 `constexpr` 数组

python - 请求遍历字典中的每一行: how to fix

python - 我怎样才能将这个格式化的字符串转换成键值字典形式?

swift - MKOverlay 自定义描边 - CGPath

c++ - 如何在不关闭VTK渲染窗口的情况下使代码流畅?

c++ - 在 "for"语句中声明 for 循环的计数器是否更有效?