[英]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.