Freeing allocated memory from a vector!

I've got a vector:

std::vector<C_Trigger*> tRegister;



Then I throw in pointers like this:

// trigger1 activates event1
C_Trigger* trigger1 = new C_Trigger(standOnTrigger); // Stand on cell trigger
trigger1->addEvent(event1);
tRegister.push_back(trigger1);


// trigger2 activates event2
C_Trigger* trigger2 = new C_Trigger(standOnTriggerAndKeyPress);
trigger2->addEvent(event2);
tRegister.push_back(trigger2);



Now, I would like to free up the memory I've allocated for trigger1 and trigger 2.
If Handle() returns true, that means the trigger has been used and should be deleted.



// Loop through triggers!

for(int i=0; i < tRegister.size(); i++) {

if(tRegister[i]->Handle()){ // True is set to kill! :D


// This is where the problem is..
C_Trigger* temp = tRegister[i];
delete temp;

tRegister.erase(tRegister.begin()+1);

}
}


I'm not too sure on the whole itterator idea.. Please, if you spot something I'd be really glad if you told me about it.

Cheers!

Here's the pastebin link, easier to read ;)

http://pastebin.com/d1db1036d
In simple, iterator is a type of pointer that is of same type your container or vector associated with and helps you to traverse the vector as easy as an incrementer or decrementer counter.

In your case, you would declare it as:

std::vector<C_Trigger*>::iterator tRegIterator;

And in place of
for(int i=0; i < tRegister.size(); i++) {

it would be:
for(tRegIterator=tRegister.begin(); tRegIterator != tRegister.end(); tRegIterator++) {

And the erase() only cleans the vector`s element but does not delete the pointed-to member. The code snippet would look like:



for(tRegIterator=tRegister.begin(); tRegIterator != tRegister.end(); tRegIterator++) {

if(tRegister[tRegIterator]->Handle()){ // True is set to kill! :D


// This is where the problem is..
delete tRegister[tRegIterator];

tRegister.erase(tRegIterator);

}

PS: I assume you want to erase the element that the handle() is true for. tRegister.begin()+1 does not seem to be right, and I changed it to the the element being erased.

That is it, it should work now. Check it out.

Good luck :)
<3
Topic archived. No new replies allowed.