Home > Mobile >  How to for loop with iterators if vector type is parent of two child types filling vector
How to for loop with iterators if vector type is parent of two child types filling vector

Time:03-29

I have this problem:

this is my loop for previously used child type

std::vector<Coin>::iterator coin;

for (coin = coinVec.begin(); coin != coinVec.end();   coin)
{

    sf::FloatRect coinBounds = coin->getGlobalBounds();

    if (viewBox.intersects(coinBounds))
    {

        if (playerBounds.intersects(coinBounds))
        {
            coin = coinVec.erase(coin);
            break;
        }
        else coin->setTextureRect(currentFrame);

    }
}

And the similar one for std::vector<Heal>.

I rebuild my code structure to: Coin is now child of Collectables.

There is now only one vector: std::vector<Collectables> which contains all collactable child classes objects like Coin, Heal etc.. Is there a way to make the code work with only one loop and iterators? If yes, how would you do that?

Thanks

CodePudding user response:

I find out that my code is so universal, that I dont need to separate vector elements at all.

My solution here:

std::vector<Collectables>::iterator collect;

for (collect = collectVec.begin(); collect != collectVec.end();   collect)
{

    sf::FloatRect collectBounds = collect->getGlobalBounds();

    if (viewBox.intersects(collectBounds))
    {

        if (playerBounds.intersects(collectBounds))
        {
            collect = collectVec.erase(collect);
            break;
        }
        else collect->setTextureRect(currentFrame);

    }
}

And if you really need to separate elements, try this:

if (collect->getType() == ResourceManager::enums::textures::coin)
{

} else
    if (collect->getType() == ResourceManager::enums::textures::health)
    {

    }

Where getType stores simply int id matching enum value.

CodePudding user response:

Although seems that you have solved the problem, it is probably worth to tell how would you solve the initial problem. As mentioned in the comments storing elements in the vector would result in object slicing, e.g.

std::vector<BaseClass> vect;

The elements of the vector would be able to store information about objects, which is common for classes, aka defined in BaseClass. If you want to be able to perform polymorphism(which you are trying to achieve in the example), you should store vector of pointers like this.

std::vector<BaseClass*> vect; 

Each pointer would point to the address of the element, and thus object slicing won't happen.

  • Related