重载运算符以获取优先级队列

时间:2013-11-15 19:02:28

标签: c++ data-structures compiler-errors operator-overloading priority-queue

我正在尝试重载()运算符以使用我的Cell对象的优先级队列。

每个Cell对象都具有以下功能:

static int GetCost(const Cell first, const Cell second);

将成本从first单元格返回到second

现在我有一个像这样的优先级队列:

priority_queue<Cell*, std::vector<Cell*>, Comparator> path;

我的优先级队列必须是指针队列。

我想根据Cell的成本(从GetCost()返回)在优先级队列中添加Cell,所以在Web上创建了一些示例之后,我尝试这样做:

struct Comparator
    {
        bool operator()(const Cell lfs, const Cell rhs)
        {
            return Cell::GetCost(lfs, rhs) < Cell::GetCost(rhs, lfs);
        }
    };

但这给了我错误:

Error 4 error C2664: 'bool AI::Comparator::operator ()(const Cell,const Cell)' : cannot convert argument 1 from 'Cell *' to 'const Cell'

我已经尝试将其更改为:

bool operator()(Cell* const lfs, Cell* const rhs)
        {
            return Cell::GetCost(*lfs, *rhs) < Cell::GetCost(*rhs, *lfs);
        }

但这给了我一个更糟糕的错误:

Error 4 error LNK2019: unresolved external symbol "public: static int __cdecl Cell::GetCost(class Cell,class Cell)" (?GetCost@Cell@@SAHV1@0@Z) referenced in function "public: bool __thiscall AI::Comparator::operator()(class Cell * const,class Cell * const)" (??RComparator@AI@@QAE_NQAVCell@@0@Z)

我已经尝试过更改

static int GetCost(const Cell first, const Cell second)

static int GetCost(const Cell* first, const Cell* second)

我得到的错误是:

Error 4 error LNK2019: unresolved external symbol "public: static int __cdecl Cell::GetCost(class Cell const *,class Cell const *)" (?GetCost@Cell@@SAHPBV1@0@Z) referenced in function "public: bool __thiscall AI::Comparator::operator()(class Cell * const,class Cell * const)" (??RComparator@AI@@QAE_NQAVCell@@0@Z)

以下是整个GetCost:

static int GetCost(const Cell first, const Cell second)
{
    int k;
    for (k = 0; k < first.neighbors.size(); k++)
    {
        if (first.neighbors[k].cell->row == second.row &&
            first.neighbors[k].cell->column == second.column)
        {
            return first.neighbors[k].weight;
        }
    }
}

我也尝试将其更改为指针,但它不起作用。

2 个答案:

答案 0 :(得分:1)

您的优先级队列存储Cell个指针(Cell*),但您的函数会比较Cell个对象(Cell)。其中一件事情需要改变以匹配另一件事。

关于链接器错误,请在实现文件中更改:

static int GetCost(const Cell first, const Cell second)
{
    ...
}

到此:

int Cell::GetCost(const Cell first, const Cell second)
{
    ...
}

答案 1 :(得分:0)

它看起来像是一种类型不匹配的问题。请检查您在priority_queue类中调用Comparator结构的代码,验证您使用的参数。 operator()需要Cell实例或Cell引用。也许你传递了Cell to()运算符的指针。

相关问题