I was writing this code below, and found this strange behavior:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
   map<int, string> map1;
   map1[1] = "Hello";
   map1[2] = "Hello1";
   map1[3] = "Hello2";
   map1[4] = "Hello3";
   map1[5] = "Hello4";
   map<int, string>::iterator it;
   for (it = map1.begin(); it != map1.end(); /*it++*/)
   {
      cout << "Enter: " << (int)(it->first) << endl;
      if (it->first == 3)
         map1.erase(it);
      it++;
      cout << "Exit: " << (int)(it->first) << endl;
   }
   return 0;
}
The output was:
Enter: 1
Exit: 2
Enter: 2
Exit: 3
Enter: 3
Exit: 4
Enter: 4
Exit: 5
Enter: 5
Exit: 4
When I increment the iterator it only in the for loop (check the commented iterator), the output is as follows:
Enter: 1
Exit: 1
Enter: 2
Exit: 2
Enter: 3
Exit: 3
Enter: 4
Exit: 4
Enter: 5
Exit: 5
I am confused as to why in the first case, when I increment the iterator, it again points to the previous map element 4?
 
     
     
    