c++ where does a iterator point after it is erased?

Viewed 43

I have following code,

    std::map<int, int> test_m;
    test_m[1] = 1;
    auto it = test_m.begin();
    auto n_it = next(it, -1);
    auto nn_it = next(n_it, -1);
    std::cout<< it->second << std::endl;
    std::cout<< nn_it->second << std::endl;
    if (n_it == test_m.end()) {
        std::cout << "n_it is end." << std::endl;
    }
    test_m.erase(it);
    
    if (nn_it != test_m.end()) { // this line generate error
        std::cout<< nn_it->second << std::endl;
    }

It seems after erase it, I cant compare nn_it with map.end(), how do I know it is invalid?

0 Answers
Related