我正在尝试弄清楚当两个给出如下时如何比较结构中的数据:
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/