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

Error with custom struct: "VS 2015 error C2678: binary '<': no operator found which takes a left-hand operand of type 'const Node'"

我正在尝试在二维网格上创建 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_;
}

感谢您的宝贵时间。

如果不重载 operator< 或定义您自己的自定义比较器,您就无法拥有某些东西的 std::set。 std::set 通常是一个 red-black 树,其中的对象是键,这需要能够比较键。

因此,您可以为节点制作一个运算符<,也可以制作一个自定义比较器。关于自定义比较器的信息 here

std::set is an associative container that contains a sorted set of unique objects of type Key. Sorting is done using the key comparison function Compare.

source

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

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

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

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

std::set is an associative container that contains a sorted set of unique objects of type Key. Sorting is done using the key comparison function Compare.

因此您需要定义比较运算符或给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;
}