[英]c++ - sorting std::vector in pathfinding
我正在尝试在我正在开发的游戏中实现粗略的寻路示例。 我到了需要对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;
}
注意:您没有包括错误消息,因此以下答案或多或少取决于视图编译:
sortF()
,而不是sortF
error: expected primary-expression before ‘)’ token std::sort(open.begin(), open.end(), sortF); ^
您需要一个sortF
实例,而不是struct sortF
类型。 使用sortF()
创建一个临时对象,或者使用函数代替函子:
bool sortF(const Tile& a, const Tile& b)
{
return a.f > b.f;
}
Tile*
与const Tile&
您在std::vector<Tile*>
上使用std::sort
,但是比较函数使用const Tile&
作为参数。 使用std::vector<Tile>
或更正函数中的类型:
bool sortF(const Tile* a, const Tile* b)
{
return a->f > b->f;
}
由于std::vector
的元素为Tile*
类型,因此比较std::vector
两项的函数必须采用两个Tile*
。
struct sortF
{
bool operator()(Tile* ap, Tile* bp) const
{
return a->f > b->f;
}
};
您绝对必须在比较器函数中更改对指针的引用。 您没有告诉您有关指针和整数之间比较的错误的确切位置,但我相信它发生在这一行:
std::remove(open.begin(), open.end(), 0);
std :: remove()采用容器的值类型,而不是索引。 您想做的可能是
open.pop_front()
也就是说,此操作以及排序都需要相当长的时间,并且正如Javi V所评论的那样,此处最好使用堆结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.