我正试图为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;我还试图用SFML2.1和2.2进行编译,但没有成功。你知道我为什么会犯这个错误吗?非常感谢:)
发布于 2014-12-18 19:08:54
sf::Vector2<T>没有operator<,但是为了在std::map中使用它作为密钥,它需要这样一个操作符。在某种程度上,您有两个选项,而不需要修改Vector2.hpp:一个复杂的方法,一个简单但不需要的方法。
Easy
简单地从一个固定的大小来制作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==可能不会给出预期的结果,不管是否进行模糊比较。
,否则
将一些operator<添加到Vector2.hpp和Vector2.inl中,但是您需要它。
https://stackoverflow.com/questions/27553850
复制相似问题