0

I use this code to remove elements from map container that equal to some int.

for(auto x:m){
  if((x.second)==element)m.erase(x.first);
}

As result Segmentation fault. I also tried this:

for(map<int,int>::iterator i=m.begin();i!=m.end();i++){
  if((i->second)==element)m.erase(i);
}

Same result. If you put i++ into if/else program will freeze/loop or something. How can I fix this?

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
Mbroo
  • 29
  • 5

2 Answers2

5

erase() invalidates the iterator being used by the for loop. Fortunately, erase() itself returns an iterator to the next entry, so the correct loop would look like this instead:

for (map<int,int>::iterator i = m.begin(); i != m.end(); )
{
    if (i->second == element)
        i = m.erase(i);
    else
        ++i;
}
john
  • 85,011
  • 4
  • 57
  • 81
2

In addition to @john's answer, if your C++ Standard Library implementation supports it, you can invoke the std::erase_if(map, condition) helper:

std::erase_if(m, [](const auto& item) {
    auto const& [key, value] = item;
    // Write your erasing condition here, e.g.:
    // return value == element;
});
Mr.C64
  • 41,637
  • 14
  • 86
  • 162