繁体   English   中英

我的代码不适用于std :: map和sf :: Vector2i

[英]My code doesn't work with std::map and sf::Vector2i

我正在尝试为SFML创建一个寻路系统,但由于编译错误,我陷入困境。 当我尝试将一个元素添加到我的std :: map时,会发生此错误。 这是标题代码:

#include <SFML/Graphics.hpp>
#include <list>
#include <map>

class Node {
    public: 
        float cout_g, cout_h, cout_f;
        sf::Vector2i parent;
};

class Pathfinding
{
    public: 
        Pathfinding(sf::Vector2i);
        std::list<sf::Vector2i> searchPath(sf::Vector2i endpoint,sf::Vector2i startpoint);

    private: 
        std::map<sf::Vector2i,Node> closedList;
        std::map<sf::Vector2i,Node> openList;
};

这是源代码:

#include "Pathfinding.h"

Pathfinding::Pathfinding(sf::Vector2i coords)
{
}

std::list<sf::Vector2i> Pathfinding::searchPath(sf::Vector2i endpoint, sf::Vector2i startpoint)
{
    Node startNode;
    startNode.parent.x = 0;
    startNode.parent.y = 0;
    openList[startpoint] = startNode;
    std::list<sf::Vector2i> list;
    return list;
}

这是游戏循环:

#include "Pathfinding.h"

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"A* Test");
    Pathfinding pathfinder(sf::Vector2i(800,600));
    while(window.isOpen())
    {
        sf::Event event;
        while(window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed) window.close();
        }
        std::list<sf::Vector2i> path = pathfinder.searchPath(sf::Vector2i(3,3),sf::Vector2i(45,55));
        window.clear(sf::Color::White);
        window.display();
    }
    return 0;
}

这段代码根本不是函数,我把它减少到调试的最小值。
我真的不明白它给出的错误代码: http//pastebin.com/mBVALHML (我在Pastebin上发布它因为它真的很长)。 我在这个错误中唯一理解的是问题来自这一行:

openList[startpoint] = startNode;

我也尝试使用SFML 2.1和2.2编译,但它没有用。 所以你知道为什么我会收到这个错误,也许是如何修复它的? 非常感谢 :)

sf::Vector2<T>没有operator<但是为了将它用作std::map的键,它需要这样的运算符。 你不知何故有两个选项,无需修改Vector2.hpp :一个复杂的,一个简单但不是那么想要的方式。

简单

只需从固定大小制作map ,例如

/*some function-head-thing*/(sf::Vector2u size)
{
    for(unsigned int y = 0U; y < size.y; ++y)
        for(unsigned int x = 0U; x < size.x; ++x)
            map[x + y * size.x] = /*some init value*/
}

要访问地图中的元素,您始终需要知道大小,但它仍然很简单: map[x + y * size.x]

复杂

由于operator==是为sf::Vector2<T>定义的,你只需要添加为sf::Vector2<T>指定的std::hash ,然后你可以用std::unordered_map替换地图。 也许是这样的:

namespace std
{
    template <class T>
    struct hash<sf::Vector2<T>>
    {
        std::size_t operator()(const sf::Vector2<T>& v) const
        {
            using std::hash;

            // Compute individual hash values for first
            // and second. Combine them using the Boost-func

            std::size_t tmp0 = hash<T>()(v.x);
            std::size_t tmp1 = hash<T>()(v.y);

            tmp0 ^= tmp1 + 0x9e3779b9 + (tmp0 << 6) + (tmp0 >> 2);
         }
    };
}

但是如果你想使用sf :: Vector2f要小心! 最好添加一个static_assert来限制T的使用,它不应该是浮点数,因为operator==可能不会给出预期的结果,无论模糊比较与否。

除此以外

Vector2.hppVector2.inl添加一些operator< ,但是你需要它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM