So, what I stumbled upon is that:
std::map<double, int> map1;
std::map<double, int> map2;
map1[2.5] = 11;
map1[3.5] = 12;
map2[2.5] = 21;
map2[3.5] = 22;
std::map<double, int>::iterator iterMap1 = map1.find(2.5);
//I will now try to erase a key/value pair in map2 with an iterator
//that points to map1. This is bad/wrong. But I am surprised
//this is allowed.
map2.erase(iterMap1);
//what do you think would be printed?
print(map1);
print(map2);
Can someone please explain this behavior? I believe this shouldn't be allowed.
The output that I get is:
Map1
2.5 11
Map2
2.5 21
3.5 22
This doesn't make sense to me. Thanks.
What do you mean it is allowed? It is disallowed in the standard and will cause undefined behavior, but that does not mean that the compiler must yell at you for attempting it.
In the general case this cannot be checked by the compiler. The map and the iterator could be passed to a function and there would not be any way of knowing whether the iterator refers to the container or not, so the compiler cannot be forced to diagnose it.
It is up to the programmer to write a valid and correct program. The compiler is there to help but not babysit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With