0

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?

tesla1060
  • 2,621
  • 6
  • 31
  • 43
  • 1
    You just know, because it was erased. :-) And end() isn't a general invalid iterator anyway, so why would it compare (or not compare) to that? – BoP Sep 23 '22 at 11:06
  • 2
    As with pointers, there is no "validity check" for iterators. You need to keep track of this yourself. – molbdnilo Sep 23 '22 at 11:08

0 Answers0