2

I have an array of vector-3 values:

 struct Vector3 {
    int x, y, z;
    ...
 };

I would like to put these values into a binary search tree for quick search and finding duplicates. In a binary search tree we need to compare values to set them in a correct order. But would there be a way to compare vectors that makes sense?

I thought about comparing them by length but this will not find duplicates correctly, as two vectors can point in different directions but have the same length.

Comparing each element doesn't make sense either since it will give different results of comparison based on order in which you compare two vectors.

So does utilizing a binary search tree for multidimensional vectors makes sense? Or should I look into hash tables?

Edit: The suggested answer implements comparison between two two-dimensional vectors (points) like this (x < pt.x) || ((!(pt.x < x)) && (y < pt.y));. But there's no explanation as to how/why this comparison works.

6
  • You can can compare lexicographically Commented May 24, 2020 at 15:38
  • @ThomasSablik Thanks! How would this work for a vector? Commented May 24, 2020 at 15:43
  • Does this answer your question? How can I create a std::set of structures? Sets aren't necessarily backed by a binary search tree, but their interface behaves like one. Commented May 24, 2020 at 15:47
  • std:: vector comes with lexicographical comparison. You can copy it for your container. Commented May 24, 2020 at 15:53
  • @ThomasSablik Do I need to convert the vectors into strings before doing lexicographical comparison? Commented May 24, 2020 at 15:58

1 Answer 1

0

When dealing with performance work, I do like John Carmack does in "Masters of Doom." Do the simplest possible thing first. You could start with a binary tree with a sort function sorting by x, then y, and then z. I'd measure and if that wasn't fast enough, depending on your ranges for X, Y, and Z, I might try a hash map (maybe hashed using bitshifting based on the possible ranges for X, Y and Z), or look into storing them in an octtree.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! How would sorting by each elements in sequence look like in code?
Shouldn't it folow the following logic instead if (v1.x == v2.x) return (v1.y < v2.y); else return v1.x < v2.x; (for two-dimensional vector)?
Yeah, you're right. Sorry, cooked that part up in a rush.
Maybe return a.x < b.y || (a.x == b.x && (a.y < b.y || (a.y == b.y && a.z < b.z)));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.