I have come across this post on stack overflow and found out the way to delete elements in a list iteratively. I wanted to try the same with both map
and list
. I got a segmentation fault with list
as expected but I did not get one with map
. Why is it so??
Below are the codes for both.
Using list :
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int>l ;
l.push_back(1);l.push_back(2);l.push_back(3);l.push_back(4);l.push_back(5);
list<int>::iterator it;
for(it = l.begin();it!=l.end();it++){
l.erase(it);
cout<<"Give me some output..\n";
}
return 0;
}
Output :
Give me some output..
Segmentation fault (core dumped)
Using map :
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, int>m ;
m[1] = 1;m[2] = 2;m[3] = 3;m[4] = 4;
map<int,int>::iterator it;
for(it = m.begin();it!=m.end();it++){
m.erase(it);
cout<<"Give me some output..\n";
}
return 0;
}
Output :
Give me some output..
Give me some output..
Give me some output..
Give me some output..
Shouldn't list iterators and map iterators show the same behaviour ??
ASIDE :
The actual problem I was facing was I was using a map in a big program and trying to delete elements from it with the wrong method mentioned above and I got the segmentation fault. Then I visited the above mentioned link and resolved the issue.But shouldn't both the codes give segmentation fault. How can two codes using same snippet of code show different behaviours. Is it that one code is small, hence the compiler was able to correct that by itself??