0

I am trying to figure out how to compare data within a struct when two is given as the following:

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

The struct being:

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;
};

Where I want my method to be:

bool Node::equal_nodes(const Node&) {

}

I am aware that the best way to go about the comparison is to compare the labels of the two nodes to see if they are the same, but I do not understand how to differentiate the data separately so that they can be compared.

2
  • What does how to differentiate the data separately mean? And why equal_nodes instead of implementing operator==? Commented Mar 27, 2017 at 0:46
  • As in, I'm not sure how to pull the labels from n1 and n2 separately so I can compare them if they are the same or not. I am required to have my method be Node::equal_nodes due to project requirements otherwise I would try and use the operator== Commented Mar 27, 2017 at 0:50

4 Answers 4

3

Implementing equalNodes()in Node struct

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

Alternatively, changing equalNodes() to implement operator== in Node struct

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;
    }
};
Sign up to request clarification or add additional context in comments.

Comments

2
bool Node::equal_nodes(const Node& that) {
   if (x != that.x) return false;
   if (y != that.y) return false;
   if (label != that.label) return false;
   return true;
}

Or, better yet, implement operator ==.

Comments

1
bool Node::equal_nodes(const Node& n) {
  if (this->x == n.x && this->y == n.y && this->label==n.label )  
     return true;

  return false;
}

Comments

1

You can use std::tie for this:

#include <tuple>
//...
bool Node::equal_nodes(const Node& that) 
{ return std::tie(x, y, label) == std::tie(that.x, that.y, that.label); }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.