自定义结构错误:"VS 2015 error C2678: binary '<': no operator found which takes a left-hand operand of



我正在尝试在 2D 网格上创建 A* 算法的实现,但卡在我需要创建一组节点邻居的点。以下是我正在使用的结构。

// Holds values for x and y locations on the grid
struct Coord {
    int x, y;
};
// holds data for each node required for A*
struct Node {
    int type; // used for defining if this node is a blocker, empty, start or end
    Coord location;
    int g = 0;
    int h = 0;
    int f = g + h;
    Node *parent_; // pointer to this node's parent
    std::string debugmessage;
};

当我在这里创建此函数时出现错误:

// finds a node's neighbours for A*
std::set<Node> neighbours(Node& n_) {
    std::set<Node> neighbours_;
    Node temp = n_;
    int x = temp.location.x;
    int y = temp.location.y;
    // start at the location belonging to 'n_'
    for (y; y < HEIGHT; y++) {
        for (x; x < WIDTH; x++) {
            // east
            if (x < WIDTH - 1) {
                neighbours_.insert(astarArray[x + 1][y]);
            }
            // west
            if (x > 0) {
                neighbours_.insert(astarArray[x - 1][y]);
            }
            // south
            if (y < HEIGHT - 1) {
                neighbours_.insert(astarArray[x][y + 1]);
            }
            // north
            if (y > 0) {
                neighbours_.insert(astarArray[x][y -1]);
            }
        }
    }
    return neighbours_;
}

谢谢你的时间。

如果没有重载运算符

因此,您可以为节点创建一个运算符<或者您可以制作一个自定义比较器。有关自定义比较器的信息,请点击此处。>

std::set 是一个关联容器,其中包含一组排序的 Key 类型的唯一对象。排序是使用键比较功能比较完成的。

您必须重载运算符<为您的节点。>

许多(std(构造函数需要比较运算符才能工作。

您使用 std::set ,它不知道如何比较两个Node对象。

如前所述http://en.cppreference.com/w/cpp/container/set

std::set 是一个关联容器,其中包含一组排序的 键类型的唯一对象。使用键比较完成排序 函数比较。

因此,您需要定义比较运算符或std::set提供一个比较函子作为参数。

编译器会告诉您缺少第一个:"<">

struct Node {
    friend bool operator< (const Node& _nLeft, const Node& _nRight);
    //friend not necessary since we use struct (full public)
    ...
};
bool operator< (const Node& _nLeft, const Node& _nRight)
{
    if (_nLeft.type < _nRight.type)
        return true;
    ...
    return false;
}

相关内容

最新更新