Comparing 3d Point struct for equality

Hi all,

I have a structure of 3d points defined as such:

1
2
3
4
5
6
struct Point
{

  double x, y, z;

};


I also have a vector of vectors of points:

 
  vector< vector<Point> > possible_neurons;


What I want to test is if possible_neuron[i] == possible_neuron[k] to test for duplicate vectors of points in possible_neurons. How can I do this?

thanks
You'll have to overload the equality operator. Here is how you could do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool operator==(const std::vector<Point>& v1, const std::vector<Point>& v2)
{
	if(v1.size() != v2.size()) return false;

	for(std::vector<Point>::size_type i = 0; i < v1.size(); ++i)
	{
		if(v1[i].x != v2[i].x || v1[i].y != v2[i].y || v1[i].z != v2[i].z)
		{
			return false;
		}
	 }

	 return true;
}

You should probably also overload the inequality operator, which is quite simple now:

1
2
3
4
bool operator!=(const std::vector<Point>& v1, const std::vector<Point>& v2)
{
	return !(v1 == v2);
}

If you want, you could overload the operator for objects of type Point, then use these to simplify the above code and keep things where they belong logically speaking.
Last edited on
std::vector<> already defines both operator== and operator!=.

What you need is a comparator for Point. The simplest way, albeit using a few boost libraries:

1
2
3
4
5
6
7
8
#include <boost/operators.hpp>  // For equality_comparable<> template
#include <boost/tuple/tuple.hpp>  // For boost::tie
#include <boost/tuple/tuple_comparison.hpp>  // For operator== for tuples

struct Point : private boost::equality_comparable<Point> {
   bool operator==( const Point& rhs ) const
       { return boost::tie( x, y, z ) == boost::tie( rhs.x, rhs.y, rhs.z ); }
};


Otherwise you can just hand-code operator== and then write operator!= in terms
of operator== as filipe did.
Both responses so far seem like overkill.
All you need is to overload the comparitor for a Point:

1
2
3
4
5
6
bool operator == ( const Point& lhs, const Point& rhs )
  {
  return (lhs.x == rhs.x)
      && (lhs.y == rhs.y)
      && (lhs.z == rhs.z);
  }

Thereafter the vector can be compared properly.

Hope this helps.
That's sort of true. The boost::tie trick is more useful for implementing operator<.
Though I'd expect that if I can compare two things for equality, then I can also
compare them for inequality.

While I like (and use) Boost, the std::rel_ops namespace also provides such functionalities. It would be difficult to decide, however, whether a 3D point X < Y, without some domain-specific criteria. For (mathematical) vectors, perhaps the length of the vector (x,y,z) would be at issue?
Topic archived. No new replies allowed.