I want to modify my container while iterating over it. But the first version of the code didn't work properly. Can someone explain the reason?
// version 1
int main(){
int a=1, b=2, c=5;
std::set<int*> m = {&a, &b, &c};
for(auto mi : m){
std::cout << *mi << std::endl;
m.erase(mi);
}
}
Then I tried another version. It seems to be fine. Is there any potential trouble when I iterate like this?
// version 2
int main(){
int a=1, b=2, c=5;
std::set<int*> m = {&a, &b, &c};
while (!m.empty()){
std::cout << **m.begin() << std::endl;
m.erase(m.begin());
}
}