Re: delete map elements
"David" <clamayi@gmail.com> wrote in message
news:1174145209.019883.201170@o5g2000hsb.googlegroups.com...
Hi all,
I try to use map container and delete the elements. but there are
something wrong, please help me check it.
class test{
protected:
map<string,myclass*> tests;
public:
test();
void AddMyclass(const string& myname,const myclass &st);
~test();
};
suppose myclass has been defined before.
and
test::~test()
{
map<string,myclass*>::iterator ii;
for(ii=tests.begin();ii!=tests.end();++ii)
{
delete(ii->second);
}
tests.clear();
}
int main()
{
test my;
myclass st;
my.AddMyclass("new class",st);
}
But when the code exits from the main function, there was an error
message saying that "Object reference not set to an instance of an
object.".
I think it is caused by the test's destructor function. But I don't
know where is the problem. Please help me. Thanks
This is snippets of code I use that works.
typedef std::map<unsigned int, CEffect*> BeamEffectsType;
// ...
BeamEffectsType BeamEffects;
// ...
CEffect* Effect = new CEffect(ProjectileSpeed, Lifetime, Pos, Aim,
FireIndex, CEffect::ParticleStream);
BeamEffects.insert( std::make_pair< unsigned int, CEffect* >( Index,
Effect ) );
// ...
// Update ALL the -On-The-Fly- or Fired 'Beams' to NEW positions.
for ( BeamEffectsType::iterator it = BeamEffects.begin(); it !=
BeamEffects.end(); )
{
if ( !(*it).second->Update() )
{
delete (*it).second;
it = Client.BeamEffects.erase(it);
}
else
++it;
}
// ...
for ( BeamEffectsType::iterator it = BeamEffects.begin(); it !=
BeamEffects.end(); )
{
delete (*it).second;
++it;
}
Incidently, in this code
(*it).second;
is equivalent to
it->second;
It is just the way I prefer to do it