Sometimes STL Really Impresses Me

Sgi

I was talking to a developer today and we got to talking about the fact that the STL map spec says that it's iterator is not invalidated on insert or removal - except in cases where the iterator is on the removed object. So it got me to thinking - what happens when you invalidate an iterator?

So I wrote this code:

  #include "map"
  #include "string"
  #include "exception"
  #include "iostream"
 
  using namespace std;
 
  int main(void) {
    map<string, string> map_test;
    map<string, string>::iterator iter_map_test;
 
    map_test["AAAAA"] = "11111";
    map_test["BBBBB"] = "22222";
    map_test["CCCCC"] = "33333";
 
    iter_map_test = map_test.find("BBBBB");
 
    map_test.erase("BBBBB");
 
    try {
      string value = (*iter_map_test).second;
      cout << "got : " << value << endl;
      ++iter_map_test;
      cout << "next: " << (*iter_map_test).second << endl;
    } catch ( exception & e ) {
      cout << e.what() << endl;
    } catch ( ... ) {
      cout << "generic exception." << endl;
    }
    return(0);
  }

and the results are amazing (to me):

  $ g++ maptest.cpp -o maptest
  $ maptest
  got : 
  next: 11111
  $

So the iterator is resetting itself when invalidated. That's very interesting! Now it's not what I expected, and I'm not certain I want to risk it, but it's nice to see that there is something non-fatal about the process. That part, it seems, the spec is right on the money about.

Clever dudes.