array to vector transition

Get answers to all your basic programming questions. No Ogre questions, please!
Post Reply
User avatar
saintnick
Halfling
Posts: 51
Joined: Tue Nov 27, 2018 1:41 am
x 2

array to vector transition

Post by saintnick » Thu Mar 14, 2019 4:05 pm

I am currently changing my NPC class container from an array to a vector.

Armed NPCs currently have a targetID int that represented the index position in the array of the NPC the armed NPC is targetting.

The problem arises when an NPC is removed from the new vector container. The indexes of all NPCs change and targetID of the armed NPC no longer points to the correct NPC. (and could crash!)

To fix this I planned on adding unique npcID and uniqueTargetID ints to the NPC class. To minimize looping through the NPC vector I planned on using this only when a NPC is removed.

Code: Select all

void updateNPCTargetIDs()
{
    int i = 0;
    for (auto npc : NPCVector)
    {
        for (auto npc2 : NPCVector)
        {
            if (npc->uniqueTargetID == npc2->npcID)
            {
                npc->targetID = i;
            }
            i += 1;
        }
    }
}
The gist:
NPC class holds index number of other NPCs in the NPCVector vector. Index number is invalidated upon removal of an NPC.

The questions:
Is this code sample a good way to re-validate these indexes? Would an array give me better performance when I need to hold an index to another member in the container?
0 x

paroj
OGRE Team Member
OGRE Team Member
Posts: 750
Joined: Sun Mar 30, 2014 2:51 pm
x 116
Contact:

Re: array to vector transition

Post by paroj » Thu Mar 14, 2019 6:50 pm

https://en.wikipedia.org/wiki/Erase%E2% ... move_idiom allows you to only change one id per remove
0 x

User avatar
saintnick
Halfling
Posts: 51
Joined: Tue Nov 27, 2018 1:41 am
x 2

Re: array to vector transition

Post by saintnick » Mon Mar 18, 2019 3:09 pm

This is an example of what I think happens and why I need the udpateNPCTargetIDs function.

Vector of ten NPC (NPCVector). NPCVector[0]'s targetID is NPCVector[2]. Call erase on NPCVector[1]. NPCVector[2] through NPCVector[9] indexes shift left. NPCVector[0] is still targetting NPCVector[2] but NPCVector[2] was NPCVector[3] before the call to erase and thus the targetID has become corrupted.
0 x

Post Reply