C++ - 为什么程序在map迭代器中使用if语句崩溃?

Fri*_*der 4 c++ crash maps iterator if-statement

我是C++的新手,我正在尝试迭代地图,同时传递一个if语句.然而程序崩溃了.

请帮我修复程序.

#include <bits/stdc++.h>
#include <iostream>
#include <set>
#include <string>
#include <iterator>

using namespace std;

int main()
{
    std::map<int,int> h;
    std::map<int,int>::iterator it;

    h[1] = 2;
    h[4] = 5;
    for(it = h.begin(); it !=h.end(); it++){
        if (it->second > 4){
            h.erase(it->first);
        }
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

你正在擦除for循环中的元素,并且指向被移除元素(即it)的迭代器将被无效.那it++会引起问题.

你可以

for (it = h.begin(); it != h.end(); ) {
    if (it->second > 4){
        it = h.erase(it);  // set it to iterator following the last removed element
    } else {
        ++it;
    }
}
Run Code Online (Sandbox Code Playgroud)