loading...

Vector for() iterator returning a null (or zero) object for each iteration (solved)

mabla0531 profile image Matthew Bland ・1 min read

Update, I think I have permanent brain damage.

I have a vector of tiles for a 2d game, each tile has an x and y and a get function. If I iterate over this vector using for (Tile t : tiles) and call t.getX() it returns 0 for every tile. Why is this? Should I be using a pointer instead? More verbose code below.

for (Tile t : tiles)
{
    if (sf::IntRect(t.getX(), t.getY(), t.getX() + 32, t.getY() + 32).contains(sf::Vector2i(x, y)))
    {
        return t;
    }
    return tiles.front();
}

I later found out that the return tiles.front(); is returning always if the first tile scanned isn't solid. Therefore moving it one line down will work. I found this because visual studio said not all control paths return. Of course.

Discussion

markdown guide
 

You can try to use the STL algorithms for this kind of task and they avoid common mistakes when using loops. They should have almost the same code generated as your loop in your scenario. For example:

const auto result = std::find_if(std::begin(tiles), std::end(tiles), [](const Tile& t){
  sf::IntRect(t.getX(), t.getY(), t.getX() + 32, t.getY() + 32).contains(sf::Vector2i(x, y));
});
return (result != std::end(tiles)) ? *result : tiles.front();

You can watch the Sean Parent's C++ Seasoning video (a must watch to me) for more discussion on this topic.

Also, C++20 ranges would finally remove the stupid begin and end boilerplate. Though no standard library implementation ship that yet :-(.