C++:比较结构中的数据

标签 c++

我正在尝试弄清楚当两个给出如下时如何比较结构中的数据:

Node n1(10,10, "tens");
Node n2(20, 20, "twentys");
cout << n1.equal_nodes(n2) << endl;
cout << n1.equal_nodes(n1) << endl;

结构是:

struct Node{
  int x;
  int y;
  string label;

  Node()=default;
  Node(int i, int j, string l) :  x(i), y(j), label(l) {} ;
  string to_string () const;
  bool equal_nodes(const Node&);
  double distance(const Node &)const;
};

我希望我的方法在哪里:

bool Node::equal_nodes(const Node&) {

}

我知道比较最好的方法是比较两个节点的标签,看看它们是否相同,但我不明白如何分别区分数据以便进行比较。

最佳答案

Node 结构中实现 equalNodes()

bool equalNodes(const Node& rhs){ 
        return this->x == rhs.x && this->y == rhs.y && this->label == rhs.label;
}

或者,更改 equalNodes() 以在 Node 结构中实现 operator==

struct Node{
    int x;
    int y;
    string label;

    Node()=default;
    Node(int i, int j, string l) :  x(i), y(j), label(l) {} ;
    string to_string () const;
    double distance(const Node &)const;

    bool operator==(const X& lhs, const X& rhs){ // replace with equalNodes
        return lhs.x == rhs.x && lhs.y == rhs.y && lhs.label == rhs.label;
    }
};

关于C++:比较结构中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43036271/

相关文章:

c++ - 哪个更快 : STL queue or STL stack?

c++ - 如何在MSVC中实现EXCLUDE_FIRST_ARGUMENT宏?

c++ - 即使>>和getline都获取null输出,即使我正在使用字符串空白

c++ - 应该重载 operator = 返回 class& 或 class

c++ - while 循环外的 Ifstream 对象

c++ - 如何在不知道成员类型的情况下检查 SFINAE 是否存在成员?

c++ - 查找范围内的最大和第二大元素

c++ - C++ 桌面应用程序中的网页

c++ - 如何访问转换后的 openegl 模型 View 矩阵 [尝试过 glGetFloatv()]?

C++ 智能指针在 std::make_unique 中丢失