我正在尝试在我正在开发的游戏中实现一个粗略的寻路示例。我现在需要对 std::vector<Tile*>
进行排序我尝试通过以下方法执行此操作,但出现了一堆我无法弄清楚的错误。我还尝试将 sortF 结构中的引用更改为指针,但出现另一个错误 - Comparison between pointer and integer ('Tile *' and 'int')
.
有问题的错误是:No matching function for call to object of type 'Stage::sortF'
想知道我到底做错了什么。
(如果有人对寻路有任何意见,那也很好)
在 Stage.h 中公开
struct sortF
{
bool operator()(const Tile& a, const Tile& b) const
{
return a.f > b.f;
}
};
在Stage.cpp中
bool Stage::tilePath(Tile* start, Tile* end)
{
std::vector<Tile*> path;
std::vector<Tile*> open;
std::vector<Tile*> closed;
start->previousTile = start;
start->g = 0;
start->h = 0;
start->f = 0;
int i, j;
float g, h, f;
int sx, sy, ex, ey;
int cost;
Tile* current = start;
Tile* neighbor = NULL;
Tile* previous = NULL;
std::cout << neighbor << std::endl;
while(current != end) {
sx = fmaxf(0, current->x - 1);
sy = fmaxf(0, current->y - 1);
ex = fminf(17 - 1, current->x + 1);
ey = fminf(6 - 1, current->y + 1);
for(i = sx; i <= ex; i++) {
for(j = sy; j <= ey; j++) {
neighbor = tiles[((j - 1) * 17) + i - 1];
if(neighbor == current || !neighbor->walkable) continue;
previous = current;
if(false /* raytrace */) {
} else {
cost = (current->x != neighbor->x || current->y != neighbor->y) ? 1.4 : 1;
g = current->g + cost;
h = euclidian(neighbor, end);
f = g + h;
}
if(std::find(open.begin(), open.end(), neighbor) != open.end() ||
std::find(closed.begin(), closed.end(), neighbor) != closed.end()) {
if(neighbor->f > f) {
neighbor->f = f;
neighbor->g = g;
neighbor->h = h;
neighbor->previousTile = current;
}
} else {
neighbor->f = f;
neighbor->g = g;
neighbor->h = h;
neighbor->previousTile = current;
open.push_back(current);
}
}
}
closed.push_back(current);
if(open.size() == 0) {
return false;
}
std::sort(open.begin(), open.end(), sortF());
current = open[0];
std::remove(open.begin(), open.end(), 0);
}
return true;
}
最佳答案
注意:您没有包含错误消息,因此以下答案或多或少基于 View 编译:
sortF()
,不是sortF
error: expected primary-expression before ‘)’ token std::sort(open.begin(), open.end(), sortF); ^
You need an instance of sortF
, not the type struct sortF
. Either use sortF()
to create a temporary object, or use a function instead of a functor:
bool sortF(const Tile& a, const Tile& b)
{
return a.f > b.f;
}
Tile*
与 const Tile&
您使用std::sort
在std::vector<Tile*>
上,但是您的比较函数使用 const Tile&
作为参数。要么使用std::vector<Tile>
或者更正函数中的类型:
bool sortF(const Tile* a, const Tile* b)
{
return a->f > b->f;
}
关于C++ - 在寻路中对 std::vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27372385/