A
Alien
According to MSDN, removing elements invalidates only those iterators
that had specifically pointed at the removed elements.
But I tried following codes, and find that without the repeated
it=map_.begin();
there will be memory violation.
So, the iterator IS invalidated even if it's not the removed one.
why?
-----------
#include <map>
#include <iostream>
using namespace std;
class CCLL;
map<int, CCLL*> map_;
class CCLL
{
int i_;
public:
CCLL(){i_=0;};
CCLL(int i){i_=i;};
int getI(){return i_;};
void killI(int i)
{
for(map<int, CCLL*>::iterator it=map_.begin();it!=map_.end();it++)
{
if(it->second->getI()==i)
{
map_.erase(it);
return;
}
}
};
~CCLL(){};
};
int main()
{
map_[3] = new CCLL(3);
map_[5] = new CCLL(5);
map_[7] = new CCLL(7);
map_[1] = new CCLL(5);
for(map<int, CCLL*>::iterator it=map_.begin();it!=map_.end();it++)
{
if(it->second->getI()==5)
continue;
it->second->killI(it->second->getI());
it=map_.begin();
}
for(map<int, CCLL*>::iterator it=map_.begin();it!=map_.end();it++)
{
cout<<it->first<<"...."<<it->second->getI()<<endl;
}
}
that had specifically pointed at the removed elements.
But I tried following codes, and find that without the repeated
it=map_.begin();
there will be memory violation.
So, the iterator IS invalidated even if it's not the removed one.
why?
-----------
#include <map>
#include <iostream>
using namespace std;
class CCLL;
map<int, CCLL*> map_;
class CCLL
{
int i_;
public:
CCLL(){i_=0;};
CCLL(int i){i_=i;};
int getI(){return i_;};
void killI(int i)
{
for(map<int, CCLL*>::iterator it=map_.begin();it!=map_.end();it++)
{
if(it->second->getI()==i)
{
map_.erase(it);
return;
}
}
};
~CCLL(){};
};
int main()
{
map_[3] = new CCLL(3);
map_[5] = new CCLL(5);
map_[7] = new CCLL(7);
map_[1] = new CCLL(5);
for(map<int, CCLL*>::iterator it=map_.begin();it!=map_.end();it++)
{
if(it->second->getI()==5)
continue;
it->second->killI(it->second->getI());
it=map_.begin();
}
for(map<int, CCLL*>::iterator it=map_.begin();it!=map_.end();it++)
{
cout<<it->first<<"...."<<it->second->getI()<<endl;
}
}