Skip to main content

Interesting properties of iterators

 Erasing in map in a loop.

if you run this code:

Consider 'mp' as map<int,int>

for(auto &it : mp)
{
    a.erase(it.first);
}

This would give you a runtime error as follows:
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

This is because when you are erasing it.first from a map and then in the loop you are doing it++ and it do not exist after erasing. So, this loop will work instead:

auto it=a.begin();
while(it!=a.end())
{
  it=a.erase(it);
}


Comments

Popular posts from this blog

Competitive Prograaming From 1000 rating to 2400+

Okay, so let's talk about some strategies for competitive programming. I was once a gray coder as I was totally new to programming when I entered codeforces. FROM GRAY TO GREEN:     First of all, you need to be good at brute force and implementation. If you are a complete beginner then do 20-30 800-1200 problems and you will b good at solving A level problems in 5-10 minutes. The try to do B in a live contest in 15-30 minutes only. By only this you can shift your rating to 1200 or so. FROM GREEN TO CYAN Now, to increase your speed you just need to practice more A and B level problems. As you are now quite confident of solving A and B level problems you must now try C also which is generally of 1400-1700 rating. This require some special techniques such as prefix sum, or some simple trick methods for reducing time complexity. Now the mistake I did was I tried to learn more advanced data structures such as graphs, trees, KMP algorithm, etc and that wasn't ne...