【问题标题】:Error with custom struct: "VS 2015 error C2678: binary '<': no operator found which takes a left-hand operand of type 'const Node'"自定义结构出错:“VS 2015 错误 C2678:二进制 '<':未找到采用 'const Node' 类型的左侧操作数的运算符”
【发布时间】:2018-03-15 14:22:39
【问题描述】:

我正在尝试在 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 文档,并从它所拥有的类型中看到了它需要什么才能发挥作用。那你为什么不把它包括在这里呢?

标签: c++ visual-studio-2015 path-finding a-star stdset


【解决方案1】:

如果不重载 operator

因此,您可以为节点创建一个运算符here 的信息。

【讨论】:

    【解决方案2】:

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

    source

    你必须为你的节点重载操作符

    【讨论】:

      【解决方案3】:

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

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

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

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

      所以你需要定义比较运算符或者给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;
      }
      

      【讨论】:

      • 谢谢,这是我急于完成的任务,我只是再次使用 std::set 因为它在代码的不同部分工作,其中使用 set 是一个要求.使用 std::list 代替,还删除了完全不必要的嵌套 for 循环......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      相关资源
      最近更新 更多