2
\$\begingroup\$

So I've been making a 2D grid and pathfinder using SFML. Now I ran into a problem. I've been making a vector for the path nodes.

struct Node
{
    std::pair <int, int> node; // position of the node <x,y>
    std::pair <int, int> previous; 
    bool iswall = false; 
    sf::Vector2f rectCenter = sf::Vector2f(0, 0);
    sf::Vector2f position;

};

class Gridspot
{
    Node start;
    Node end; 
    std::vector <Node> Openset
    std::vector <Node> Closedset;
    std::vector <Node> Path;
};

I then make a function so I can set grid cell's center:

void Gridspot::calculaterectCenter(sf::Vector2f& center, int i, int j)
{

    for (auto path : Path)
    {
        if (path.node == std::make_pair(i, j))
            path.rectCenter = center; break;
    }
}

in the main:

for (auto path : cell.Path)
{
    if (i == path.node.first && j == path.node.second)
    {

sf::Vector2f center(box[i][j].getPosition().x + box[i][j].getSize().x / 2, box[i][j].getPosition().y + box[i][j].getSize().y / 2);

                box[i][j].setFillColor(sf::Color::Magenta);
                cell.calculaterectCenter(center, i, j);

    }

}   

the problem that I'm facing is that when I enter the value the vector element in question rectcenter variable doesn't change.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Please note thar questions about non-game-specific programming and syntax should be directed to our general programming sister site, StackOverflow. They get much more traffic than we do, so you'll often find your question has already been answered there — as bruglesco's link demonstrates. ;) \$\endgroup\$
    – DMGregory
    Mar 6, 2019 at 12:43

1 Answer 1

3
\$\begingroup\$

you are copying in your ranged-for loop. You should use

for (auto& path : Path)

This will pass by reference and allow you to make changes to the variable correctly.

\$\endgroup\$
3
  • \$\begingroup\$ thank you very much on the response. It solved the problem. Is there a link that could expand a bit more on this i never came across this \$\endgroup\$ Mar 6, 2019 at 5:03
  • \$\begingroup\$ @YamaraiAkizuki stackoverflow.com/q/15176104/5416291 you have a reference in your code. It's there same issue with auto ranged for loop. \$\endgroup\$
    – Summer
    Mar 6, 2019 at 5:09
  • 1
    \$\begingroup\$ @YamaraiAkizuki to expand, when you type (auto path : Path) what happens is a new object will be created with the copy-constructor of your object (in this case the default copy constructor) so later when you type path.rectCenter = ... you're modifying the local copy, not the object in the Path vector. But when you make it a reference (auto& path : Path) you're actually modifying the object in the vector. \$\endgroup\$
    – Mikael
    Mar 7, 2019 at 9:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .