Vector & Iterator Help

Vector & Iterator Help
0.0 0

#1

I know this is how vectors work

std::vector<cocos2d::Sprite*> objects;
for (auto object: this->objects)
{
//Code
}

I’m wondering how do i use the iterator. I know how to use them in normal C++ where we just increment the iterator.

I want to every now and then during a game execution, increment the iterator and use the current object. In the update fucntion every now and then during game two Rect’s will intersect causing the iterator to increment 1.

Thanks


#2

They work the same way. Nothing special because you are writing a game. You can always not use an Iterator too. They can be optional. They serve a purpose though.


#3

Would you give us a code example.

I just wanna do a condition check during the update function, and if happy increment the vector iterator.

The act on that iter pointer->object…

Otherwise just ignore and carry on


#4

How about just use integer to keep track index of object vector instead of iterator since it’s vector?


#5

You just want code to do something to a specific index in an std::vector?

for (int i=0; i < GAMEOBJECTINSTANCE->getCornVector().size(); i++)
    {
        CornSprite* c = GAMEOBJECTINSTANCE->getCornVector().at(i);
        
        if (this->getTag() == c->getTag())
        {
            GAMEOBJECTINSTANCE->getCornVector().erase (GAMEOBJECTINSTANCE->getCornVector().begin()+i);
            
            removeFromParentAndCleanup(true);
            
            GAMEOBJECTINSTANCE->decrementCornCount();
            
            return;
        }
    }

#6

Can we have a 2 dimensional Vector , like a 2 dimensional array -> int array[10][2] ? Is that possible ? Thanks very much Slack :slight_smile: for your example above. Ill be using that now


#7

I have a race game, with many tracks. Each track will have varying size of way points for a AI vehicle to follow. I want to be able pass a vector to a vehicle object function. Which can be any size. If I use a normal array, there size is static which means can pass into function :slight_smile: Make sense?


#8

Sure. You can even put other std:: objects in a Vector, like a std::pair, std::tuple, and the list continues.


#9

Perfect. :slight_smile: