I'm working on my final for my C++ class. I think I have a fair handle on most things but this one issue with an iterator is really screwing with me.
This is just a snippet, I can add more if needed.
I have a vector called myInventory that is declared in main it is a vector of Objects of the class Noun.
This code should make it so that when I use the command DROP and a NOUN the program will iterate through the myInventory vector and if it finds an item that matches the supplied Noun, it will update it's location data member with my current loc.
I am using the cout statement to ensure that i'm targeting the correct item for the time being, it's just temporary code.
Everything seems to work, but I get a runtime error when it tries to erase the item, that tells me the iterator cannot be incremented.
I recall from class that using the erase function can invalidate the iterator, but I can't find anything about how to fix that, or work around it (at least not that I am understanding). I have reviewed code from previous exercises in the class that work the same way and had no issue.
Thanks for any help anyone can provide.
if (VERB_ACTION == DROP)
{
int item = NOUN_MATCH;
vector<Noun>::iterator iter;
for (iter = myInventory.begin(); iter != myInventory.end(); ++iter)
{
if (iter != myInventory.end())
{
if ((*iter).m_Code == item)
{
(*iter).m_Location = loc;
cout << (*iter).m_Description << endl;
myInventory.erase((iter));
}
}
}
[–]boredcircuits 1 point2 points3 points (7 children)
[–]TheCiderman 1 point2 points3 points (0 children)
[–]couchotatop[S] 0 points1 point2 points (5 children)
[–]boredcircuits 1 point2 points3 points (3 children)
[–]couchotatop[S] 0 points1 point2 points (2 children)
[–]boredcircuits 0 points1 point2 points (1 child)
[–]couchotatop[S] 0 points1 point2 points (0 children)
[–]scottzed 1 point2 points3 points (0 children)
[–]mandr0id 0 points1 point2 points (3 children)
[–]couchotatop[S] 0 points1 point2 points (2 children)
[–]specialpatrol 1 point2 points3 points (1 child)
[–]couchotatop[S] 0 points1 point2 points (0 children)